Bala
Bala

Reputation: 11244

Are there any exceptions to singleton methods in Ruby?

In Ruby everything is an object. But when I try a singleton method on a number, I get type error. Are there any exceptions to the notion of everything is an object?

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

Upvotes: 4

Views: 112

Answers (1)

Holger Just
Holger Just

Reputation: 55768

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.

Upvotes: 4

Related Questions