Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixnum undefined method new

Tags:

ruby

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.

like image 201
Ram Patidar Avatar asked Feb 23 '26 09:02

Ram Patidar


2 Answers

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
like image 75
Simone Carletti Avatar answered Feb 25 '26 13:02

Simone Carletti


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
like image 29
toro2k Avatar answered Feb 25 '26 11:02

toro2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!