在方法调用之前是否创建了所有对象?
问题描述:
下面是从RubyMonk教程一些代码:在方法调用之前是否创建了所有对象?
class Shoe
def initialize(toes = 1)
@toes = toes
end
puts "1 inside the class: #{defined?(@toes).inspect}"
def i_can_haz_toes
puts "2 inside the instance: #{defined?(@toes).inspect}"
end
end
class Foot
def initialize(toes = 5)
@toes = toes
end
puts "3 inside the class: #{defined?(@toes).inspect}"
def i_can_haz_toes
puts "4 inside the instance: #{defined?(@toes).inspect}"
end
end
samurai_boot = Shoe.new(2)
samurai_boot.i_can_haz_toes
left = Foot.new
left.i_can_haz_toes
puts "5 in the `main` class: #{defined?(@toes).inspect}"
这里是输出:
1 inside the class: nil
3 inside the class: nil
2 inside the instance: "instance-variable"
4 inside the instance: "instance-variable"
5 in the `main` class: nil
我没有得到的输出顺序。在代码中,首先创建对象Shoe,然后调用一个方法,并在此之后创建对象Foot。对我来说,这应该已经打印
1 inside the class: nil
2 inside the instance: "instance-variable"
3 inside the class: nil
4 inside the instance: "instance-variable"
5 in the `main` class: nil
似乎鞋和脚都是在任何方法被调用之前创建的。这个怎么用?
答
在ruby中,class
关键字打开一个类并在该类的范围内执行ruby代码。
class Object
puts 'Hello'
end
puts 'World'
打印
Hello
World
创建一个类,如果不存在仅仅是一个副作用。
顺便提一句,def
语法只是一个表达式,它定义了一个方法并返回它的名字。