ruby how to make it so you don’t have to type .to_s to add objects together into a string

So…a little bit of java envy:
in Java you can add objects to a string and it automatically calls .toString on them and adds them in, ex:

int a = 3;
float b = 4;
String x = "an int: " + a + " and a float:" + b;# and it works.

In Ruby that’s currently

a = 3
b = 4.0
x = "an int: " + a.to_s + " and a float:" + b.to_s
# or x = "an int: #{a} and a float #{b}"

Well it turns out that this can be overcome by writing .to_str methods for those objects which you don’t want to have to write .to_s all the time for.


class Fixnum
 def to_str
   to_s
 end
end
class Float
  def to_str
   to_s
  end
end
a = 3
b = 4.0
puts "an int:" + a + " and a float: " + b # outputs an int:3 and a float: 4.0

This works well but be careful existing code might not expect it [ex: rails might not with its voodoo magic].

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>