如何让我的班级上班?

时间:2011-05-26 07:40:14

标签: ruby

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 want this to print [X:Bob, X:Bob]

2 个答案:

答案 0 :(得分:5)

覆盖班级的to_s方法:

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]

答案 1 :(得分:2)

您需要initialize,而不是init