为什么我不能在数字上定义方法?

时间:2016-06-02 07:37:14

标签: ruby singleton

在Ruby中,我可以在对象上定义方法:

x = "asht"

def x.roman
  "works!"
end
x.roman # => "works"

"asht".roman # => NoMethodError: undefined method `roman' for "asht":String

但是,这不适用于数字

def 0.roman
  "doesn't work :'("
end # => SyntaxError: (irb):5: syntax error, unexpected tINTEGER

x = 0
def x.roman
  "doesn't work :'("
end # => TypeError: can't define singleton

为什么?

0 个答案:

没有答案