user2274074
user2274074

Reputation: 1087

Ruby: Why i cant define singlteon method on fixnum class

I want to define singleton method to every integer value (object) . but i am getting error while applying singleton method.

RubyDoc says There is effectively only one Fixnum object instance for any given integer value . what does this mean ?? how it is different from other normal classes?? i am not able to interpret this line.

Upvotes: 2

Views: 121

Answers (3)

Max
Max

Reputation: 22325

I want to define singleton method to every integer value (object)

This is contradictory. The singleton class is for when you want something to apply to a single object. You want to define something for every integer object, so the singleton class is not an appropriate tool. Just use the normal class

class Integer
  def foobar
    "hey"
  end
end

3.foobar
# "hey"

If you could modify the singleton class of 3, then there would be some behaviors that only apply to the number 3 and no other number. There is no technical reason to prevent that, but trust me that it's a good thing that you can't.

There is effectively only one Fixnum object instance for any given integer value

This is talking about something else. Notice the difference:

x = []
y = []
x == y                     # true
x.object_id == y.object_id # false!

x = 3
y = 3
x == y                     # true
x.object_id == y.object_id # true!
x.object_id == 5.object_id # false

Unlike most other objects, equal fixnums are identical objects. 3 and 5 are two different instances of Fixnum, but it is impossible to have two different instances of Fixnum that are both 3. Every 3 is the same. Again, this is not a technical necessity but more of a convenience for how most programmers think about numerical data.

Upvotes: 3

anothermh
anothermh

Reputation: 10546

The Integer class is frozen by default:

1.frozen?
 => true

There only ever exists one instance of any Integer object. You don't have to do anything special to enable this. In other words, the optimization you are trying to apply is built into Ruby.

Upvotes: 2

YoTengoUnLCD
YoTengoUnLCD

Reputation: 598

It means that whenever you access some Fixnum, such as the number 1, you’re always treating with the same “instance”, this is mostly an implementation detail which ruby uses to optimize numbers.

Upvotes: 2

Related Questions