Ruby object prints out as pointer

classconstructorinitializationruby

I'm trying to create a class, which has a constructor that takes a single argument. When I create a new instance of the object, it returns a pointer.

class Adder
    def initialize(my_num)
        @my_num = my_num
    end
end
y = Adder.new(12)
puts y

What am I doing wrong?
Thanks

Best Answer

When you use new method, you get 'reference' on newly created object. puts kernel method returns some internal ruby information about this object. If you want to get any information about state your object, you can use getter method:

class Adder
  def initialize(my_num)
    @my_num = my_num
  end
  def my_num
    @my_num
  end
end
y = Adder.new(12)
puts y.my_num  # => 12

Or you can use 'attr_reader' method that define a couple of setter and getter methods behind the scene:

class Adder
  attr_accessor :my_num

  def initialize(my_num)
    @my_num = my_num
  end      
end
y = Adder.new(12)
puts y.my_num  # => 12