This is some code from my assessment. This is where I make a mistake. So I put it here as a reminder.
class Dog
attr_accessor :name
end
class Something
def bob
Dog.new
end
end
class Person < Something
attr_accessor :name
def initialize(n)
@name = n
end
def Person.whatever;end
def change_name(n)
bob().name = n
end
end
bob = Person.new('bob')
bob.change_name('Robert')
puts bob.name
The problem is in change_name
, we call self.name
, what if we call bob.name
? It dose not work, because bob
is a local variable deifine on the outer area of the class. In ruby block
is different from method
, we can use outer variable in block
, but we can not use outer variable directly in method
. We have to pass into method as an arguement.
So bob.name
can not work here. But if we inheritate from Something
, there is a magic way happens to the bob
. At first, I guesss it is some kine of variable(local variable, instance variable), but I forget there is a .
, and Inheritance
in ruby only pass methods to subclass
. So bob.
here, actually is bob().
the little dot is method invocation!!! we can not get variables to call. There is no variable then “dot” something.
They are some kind of easy but important mistakes that I make today:
- local variable can not pass from outer area to inner area of
method
, unless you pass it by the arguement - dot is method invocation
- You can pass methods from the superclass to the subclass in
inheretence
.