English 中文(简体)
因此,废墟法本身是一种方法
原标题:why does a ruby method have itself as method
  • 时间:2011-04-29 20:46:07
  •  标签:
  • ruby
def moo
   puts "moo"
end

moo.moo.moo.moo

this gives

moo
moo
moo
moo

just an oddity, I was curious if this was done on purpose and served some purpose...

最佳回答

我猜想你在青少年中重新这样做,因此,你实际上重新界定了<条码>(目标)上的方法,然后界定了<条码>中所有儿童的方法。 目的......是一切。 您的方法:

def moo
  puts "moo"
end

回归代码<>nil,并由于您界定了<代码>上的方法。 目标,NilClass也有这一方法,因此,请在NilClass上打电话<>。

如果是,

class Foo
  def bar
    1 + 1
  end
end

之后:

f = Foo.new
f.bar.bar

您:

NoMethodError: undefined method `bar  for 2:Fixnum
问题回答

也许你重新定义了<代码>上的内容。 目标。 因为Rubys是 反对意见/代码以及每一种方法的回报(以<代码>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

<代码>puts “moo” Returnnil。 从范围上看的方法可在以下任何范围内使用。 由于<代码>moo属于最高范围,所有物体均可称为:

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

如果你不希望的话,则制作moo。 私人:

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

这方面的工作不多。

你重新将 mo界定为主要物体的一种方法。 然后,用摩托车进行工作,但你的返回方法是零的(因为会带来回报)。 你没有界定NilClass#moo,因此, moo.moo应该失败,对我来说也是这样。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签