开发者

How do I get puts to work on my class?

class X
  def initialize
    @name = "Bob"
  end
  blah blah
end

puts X.new  # I want this to print X:Bob
puts [X.new, X.new] # I wa开发者_运维知识库nt this to print [X:Bob, X:Bob]


Override the to_s method of your class:

class X
  def initialize
    @name = "Bob"
  end

  def to_s
    "X:#{@name}"
  end
end

puts X.new  # prints X:Bob
puts [X.new, X.new].to_s # prints [X:Bob, X:Bob]


You need to have initialize, not init.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜