Ruby object prints out as pointer

后端 未结 4 1446
感动是毒
感动是毒 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

    You aren't doing anything wrong. Assuming you see something like # then in Ruby this is just the default representation of the object that you've created.

    If you want to change this behaviour to be more friendly when you pass your object to puts you can override the to_s (to string) method. e.g.

    class Adder
      def initialize(my_num)
        @my_num = my_num
      end
    
      def to_s
        "Adder with my_num = #{@my_num}"
      end
    end
    

    then when you do puts y you'll see Adder with my_num = 12

    You can also override the inspect method which is what is used, for example, when the Ruby irb console prints the representation of your object e.g.

    class Adder
      def inspect
        to_s # return same representation as to_s
      end
    end
    

    then in irb:

    >> y = Adder.new 12
    => Adder with my_num = 12
    

提交回复
热议问题