0

Theoretical question

I'm trying to find new practical ways to convert integers into strings and the other way around. I only know the .to_s ; .to_i ; .to_f methods and would like to know if there are other ways to do to it without writing + to put together the variables. For example:

var1 = 16

puts 'I\'m ' + var1.to_s + ' years old.'

In longer codes is getting tiring writing all this to just convert a integer to a string.

By the way I also found this Timer program here on Stack and the #{ is an example of what I'm trying to do. Adding an integer to a string without + and .to_s But I don't know how it works.

30.downto(0) do |i|
  puts "00:00:#{'%02d' % i}"
  sleep 1
end

Thank you in advance for the suggestions!

1
  • 1
    The documentation for string literals is worth reading. It explains escape sequences, interpolation, the difference between '...' and "...", introduces %q(...) and %Q(...) and more. Commented Oct 2, 2020 at 8:21

2 Answers 2

4

Ruby has a pretty powerful string interpolator feature using #{...} where that can contain fairly arbitrary Ruby code. The end result is always converted to a string using, effectively, to_s.

That is you can do this:

puts "00:00:#{'%02d' % i}"

Where that gets stringified and then interpolated.

This is roughly the same as:

i_str = '%02d' % i
puts "00:00:#{i_str}"

Where that is effectively:

i_str = '%02d' % i
puts "00:00:%s" % i_str

You could also combine that into a single operation:

puts "00:00:%02d" % i

Where you generally use interpolation or sprintf-style template strings, not both at the same time. It keeps your code cleaner since only one mechanism is in play.

The only reason .to_s is needed when doing concatenation is Ruby is very particular about "adding" together two things. x + y has a completely different outcome depending on what x and y are.

Consider:

# Integer + Integer (Integer#+)
1 + 2
# => 3

# Array + Array (Array#+)
[ 1 ] + [ 2 ]
# => [1,2]

# String + String (String#+)
"1" + "2"
# => "12"

Note that in each case it's actually a different method being called, and the general form of x + y is:

x.send(:+, y)

So it's actually a method call, and as such, each method may impose restrictions on what it can operate on by emitting exceptions if it can't or won't deal.

Sign up to request clarification or add additional context in comments.

5 Comments

Ohh, so the '%02d' has nothing to do with the string interpolation
To be technical, that's a form of interpolation, in effect, but not using the #{...} string interpolation mechanism. Ruby, like C, Python, Perl and others, supportsprintf notation for strings when using the String#% method. What it does is gives you more control over how that value is interpolated in terms of a template. The #{...} method requires you to do all the formatting yourself.
But the only thing I'm missing is what the d stands for?
If you follow that documentation link it links through to the full table of placeholders where d represents "argument as a decimal number".
Additionally we could coerce a String/Integer combo e.g. class String;def coerce(other); [other.to_s,self];end;end then 1 + "s" #=> "1s"(explicit coercion) alternatively class Integer; alias_method :to_str, :to_s;end then "s" + 1 #=> "s1" (implicit coercion)
2

It's called string interpolation. For example:

puts "I\'m #{var1} years old."

The way it works is this:

  1. You have to enclose the string in double quotes, not single quotes.
  2. You put your variable inside this: #{}, e.g. "#{variable}".

This will always convert non-string variables into strings, and plug (i.e. interpolate) them into the surrounding string.

3 Comments

So the double quotes are important, I didn't know that. Thank you!
You don't have to escape the single quote when using doubles quotes. (makes the string easier to read)
@Stefan Right, you can use single quotes inside double quotes, and also double quotes inside single quotes, without escaping them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.