Ruby object prints out as pointer

后端 未结 4 1624
感动是毒
感动是毒 2021-02-02 06:50

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 Adde         


        
4条回答
  •  感动是毒
    2021-02-02 07:14

    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
    

提交回复
热议问题