如何让我的班级上班?

ale*_*loh 3 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]
Run Code Online (Sandbox Code Playgroud)

ham*_*mar 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]
Run Code Online (Sandbox Code Playgroud)

  • @alexloh,请注意该方法名为`initialize`,而不是`init`.此外,您可以改进代码以使用"#{self.class.name}:#{@ name}"`以便类名不是硬编码的. (3认同)