Ram Patidar
Ram Patidar

Reputation: 666

Fixnum undefined method new

When I tried fixnum.new is giving undefined method error.

Fixnum.new  # undefined method `new' for Fixnum:Class (NoMethodError)

Why its give undefined method. What mechanism behind the fixnum class. please explain.

If I want to make some class like fixnum (A class without new method) then what should I do?

I am going with below code but I am feeling its bad code.

class TestClass < Fixnum
end

When I tried to create new object like below:

TestClass.new #undefined method `new' for TestClass:Class

is this correct way? or if you have another way please explain here.

Upvotes: 3

Views: 2342

Answers (3)

toro2k
toro2k

Reputation: 19228

If I got your question right, you are trying to write a class that is not instantiatable using the new method. You could borrow the idea from the Singleton module and make the new (and allocate) method private:

class Whatever
  private_class_method :new, :allocate
end

Whatever.new
# NoMethodError: private method `new' called for Whatever:Class

Upvotes: 1

Simone Carletti
Simone Carletti

Reputation: 176402

As I explained in this answer, Fixnum doesn't provide a .new method. That's because you expect to create a new Fixnum (or a descendant such as Integer or Float) in the following way

1.3
1

and because, despite they are objects, there are no multiple instances of a Fixnum. In the same answer I also explained how you can use a proxy class around objects that doesn't offer such initialization.

Here's a code example

class MyFixnum < BasicObject
  def initialize(value)
    @fixnum = value
  end

  def inc
    @fixnum + 1
  end

  def method_missing(name, *args, &block)
    @fixnum.send(name, *args, &block)
  end
end

m = MyFixnum.new(1.3)
m.to_i
# => 1

Upvotes: 2

Shoe
Shoe

Reputation: 76240

Because there are Fixnum objects for every (and only) integer value. No other objects should be created. Therefore inheriting from Fixnum is, probably, not a good idea.

You may want to use composition instead:

class TestClass
    attr_reader :num # fixnum
end

Upvotes: 0

Related Questions