Ruby – How do I learn in 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]
to_s method of overriding 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 ]

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]

Override the to_s method of the class:

class X
def initialize
@name = "Bob"
end

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

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

Leave a Comment

Your email address will not be published.