why does a ruby method have itself as method
def moo
puts "moo"
end
moo.moo.moo.moo
this gives
moo
moo
moo
moo
just an oddity, I was curious if this w开发者_Python百科as done on purpose and served some purpose...
I'm guessing you're doing that in console, so you're actually defining the method on the Object
, which then defines the method on all the children of Object
... which is everything. So your method:
def moo
puts "moo"
end
Returns nil
, and because you defined the method on Object
, NilClass
has the method as well, so you can call moo
on NilClass
.
If you do:
class Foo
def bar
1 + 1
end
end
And then:
f = Foo.new
f.bar.bar
You get:
NoMethodError: undefined method `bar' for 2:Fixnum
Perhaps you're defining something on the Object
class. Because everything in Ruby is an Object
and every method returns something (defaulting to nil
), you can call that method on its own result. The moo
method returns nil
, and so what you are doing is calling moo
first on the global object, and then on each nil
returned.
You can more explicitly do this:
class Object
def moo
puts 'moo'
end
end
If you generally want to chain methods, you could try this:
class Mooer
def moo
puts 'moo'
self
end
end
a = Mooer.new
a.moo.moo.moo.moo.inspect
puts "moo"
returns nil
. A method from a scope can be used in any scope below. As moo
is in top scope, all objects can call it:
"teste".moo # => prints "moo"
If you don't want that, make moo
private:
private :moo
moo # => ok
nil.moo # => NoMethodError
moo.moo # => prints once and raise NoMethodError
That shouldn't work.
You're defining moo as a method on the 'main' object. Calling moo should then work, but your method returns nil (because puts returns nil). You didn't define NilClass#moo, so moo.moo should fail, and does for me.
精彩评论