ruby 2.2.1p85
mac Mavericks
This is a Ruby language question.
As a result of executing the source code below, there are two things you don't understand.
① Why is the output of the global variable $b "nill"?
② Why is "A.new==self" not true when calling the hoge2 method?
class A
$a = self
def hoge
$b = self
end
def hoge2
puts self
puts A == self
puts A.new==self
end
end
puts A == $a, A.new == $b
p$a
p$b
A.new.hoge2
The results are as follows:
true
false
A
nil
# <A:0x007fd8ab82a088>
false
false
That's all.
Thank you for your cooperation.
This is because the hoge method has never been run in the source code above.For example,
A.new.hoge
If you run at least once, $b
represents an object in the A
class.More importantly, the method defined by def
is never executed until the method is actually called.
The new method is used to generate new objects for that class. What you are comparing in the A.new==self
line is the object generated in A.new
and the object generated in A.new
in A.new
are the same object in A.new
.
For example, if you execute the following code,
class A
def hoge2
puts self
puts A == self
local_a_object = A.new
puts local_a_object
puts local_a_object == self
end
end
a_object = A.new
a_object.hoge2
The result is:
#<A:0x007fe3141af5f0>
false
# <A:0x007fe3141af4b0>
false
The symbol 0x007fe...
is the id of the object. hoge2
compares different objects, so the result of ==
is false
.
Among the methods, self
refers to the object on which the method is called.In class definitions (or module definitions), self
refers to the class or module itself that is defined.
If you read the meta-programming ruby, you may be able to learn more about this.
© 2024 OneMinuteCode. All rights reserved.