Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

question from:https://stackoverflow.com/questions/8125946/ruby-object-prints-out-as-pointer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
282 views
Welcome To Ask or Share your Answers For Others

1 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...