alexloh
alexloh

Reputation: 1616

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

Upvotes: 3

Views: 89

Answers (2)

hammar
hammar

Reputation: 139930

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]

Upvotes: 5

Andrew Grimm
Andrew Grimm

Reputation: 81631

You need to have initialize, not init.

Upvotes: 2

Related Questions