Why isn’t to_s being overwritten?

Asked

Viewed 44 times

0

In Ruby you can override methods, even "default" language classes. I just wanted to know why the code I did below does not overwrite properly.

class Oi
end

class Ola
  def to_s
    puts "Olá!"
  end
end

oi = Oi.new
ola = Ola.new

puts oi
puts ola

The exit is:

#<Oi:0x000055aa6f9c1bd8> Olá!
#<Ola:0x000055aa6f9c1b88> ```

The method to_s class Ola had not been superscripted? Why does he print #<Ola:0x000055aa6f9c1b88>?

1 answer

0


The to_s must return a value of type string that makes sense to that object and whoever receives this value does whatever you want with it, for example the puts will print this text. When you have it printed inside the to_s, is not returning a valid value, does not return a text, the puts inside the method makes the return null, and then he considers that you do not have a valid value and keeps returning a default value.

Returning a value that makes sense everything works as it should:

class Oi
end

class Ola
    def to_s
        "Olá!"
    end
end
oi = Oi.new
ola = Ola.new
puts oi
puts ola

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.