4

在 Ruby 中,一切都是对象。但是,当我尝试对数字使用单例方法时,会出现类型错误。一切都是对象的概念有什么例外吗?

a_str = "Ruby"
a_num = 100

def a_str.bark
  puts "miaow"
end

a_str.bark #=> miaow (Good Cat!)

def a_num.bark
  puts "miaow"
end

a_num.bark #=> TypeError: can't define singleton method "bark" for Fixnum
4

1 回答 1

4

Numbers are kind of special as they actually don't exist as real objects in memory. This would be unfeasible as there are infinite many of them.

Instead, Ruby emulates them being objects using certain conventions. i.e. you will notice that the object_id of a Fixnum is always 2 * i + 1 (with i being the number). Using this convention, Ruby can emulate the numbers that are represented as actual plain numbers on the CPU for performance and space constraints to look like objects to your Ruby program.

As Fixnums don't actually exist as discrete objects in memory, you can't change them individually. Instead, numbers are considered immutables. They can mostly be used as objects, but you can't change them as they are not actual discrete objects. There are a few other immutable objects in Ruby, e.g. false, true, nil.

In comparison, the string will be handled as a discrete ruby object that can be changed and is not immutable. It thus behaves like the majority of all the other Ruby objects you will encounter.

于 2013-03-21T12:02:47.800 回答