Can someone help me make sense of the following? I have the following code in test.rb:
class Dog
end
// bark is declared outside of Dog class
def bark
puts 'W开发者_高级运维oof!'
end
then in irb:
>> source 'test.rb'
>> a = Dog.new
=> #<Dog:0x117f614>
>> a.bark
Woof!
=> nil
Why does method bark
exist in Dog instance even though it is declared outside of the class? Because it's in the same file? Thanks!
When you create a method in the "global" scope (outside of any class), that method is made a private method of Object:
#!/usr/bin/ruby1.8
class Dog
end
p Object.respond_to?(:bark, true) # => false
def bark
puts "Woof!"
end
p Object.respond_to?(:bark, true) # => true
Object is in the ancestry chain of all objects, including Dog:
dog = Dog.new
p dog.class.name # => "Dog"
p dog.class.superclass.name # => "Object"
Therefore dogs (and indeed all objects) now know how to bark. However, the method being private, you'll have to use instance_eval to call it with an explicit receiver:
dog.instance_eval { bark } # => "Woof!"
Or you can call it with an implicit receiver with no gymnastics needed:
bar # => "Woof!"
Your exact example doesn't work in Ruby 1.9. (Apart from the bad comment syntax.)
However, declaring a method in the top level scope will make it a private method on Object
, apparently:
>> Object.private_methods.include? :bark
=> true
Perhaps in your Ruby (1.8?), this is a public method?
精彩评论