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
CodePudding user response:
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.