2

The bug on line 11 is put there on purpose. I am curious about how pry works in this example.

In the code below, when I enter pry, if I type name I get nil, which means that pry is outputting the value of the local variable which will be initialized on line 11. However, there is a getter method name and if I output its value on line 9 I get "Nemo".

Does pry first looks for local variables in a method? If so, how come that name is not undefined on line 9?

class Animal               
  attr_accessor :name      
                            
  def initialize(name)      
    @name = name            
  end                       
                            
  def change_name    
    binding.pry  
    p name   
    name = name.upcase      
  end                       
end                         
                            
fish = Animal.new('Nemo')     
p fish.name # => 'Nemo'       
p fish.change_name      
SrdjaNo1
  • 755
  • 3
  • 8
  • 18

1 Answers1

2

name = is a variable assignment, which means name is a local variable.

Ruby anticipates this and interprets all instances of name in that method to be as such. It seems like psychic knowledge, but remember Ruby has already read and compiled this function long before it is actually executed.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Thank you. What I am not sure is why `pry` doesn't see getter `name` method instead of the local variable since when we output `name` on line `9` it outputs `Nemo` correctly? – SrdjaNo1 Jul 26 '22 at 07:38
  • Ruby variables and implicit method calls are, syntax-wise, identical. If you want to force the method, use `self.name` to be explicit. – tadman Jul 26 '22 at 08:15