Why is the ruby ​​method itself a method

def moo
   puts "moo"
end

moo.moo.moo.moo

this gives

moo
moo
moo
moo

just a strangeness, I was curious if this was done on purpose and served some purpose ...

+5
source share
4 answers

I assume you are doing this in the console, so you are actually defining a method on Object, which then defines a method for all the children Object... which is all. So your method:

def moo
  puts "moo"
end

Returns nil, and since you defined a method on Object, NilClassalso has this method, you can call mooon 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
+5
source

, - Object. Ruby Object, - ( nil), . moo nil, , , moo , nil.

:

class Object
  def moo
    puts 'moo'
  end
end

, :

class Mooer
  def moo
    puts 'moo'
    self
  end
end

a = Mooer.new
a.moo.moo.moo.moo.inspect
+1

puts "moo" nil. . moo , :

"teste".moo # => prints "moo"

, moo private:

private :moo
moo # => ok
nil.moo # => NoMethodError
moo.moo # => prints once and raise NoMethodError
0

.

You define moo as a method on the "main" object. Then the moo call should work, but your method returns nil (because puts returns nil). You did not define NilClass # moo, so moo.moo should fail and do it for me.

0
source

All Articles