2

I have confusion for using expression interpolation in method. Initially I thought I can pass any kind of expression like let's say name.capitalize, but I can pass without expression interpolation too. Here is the two cases. Just execute below two methods on irb, I have same result for both method. I am using Ruby 1.9.3

1.

def say_goodnight(name)
 result = "Good night, " + name.capitalize
 return result
end

puts say_goodnight('uncle')

2.

def say_goodnight(name)
  result = "Good night, #{name.capitalize}"
  return result
end

puts say_goodnight('uncle')

Both way it will produce output like

Good night, Uncle

So my question is When Should I use expression interpolation in Ruby? and When Should I use parameter in Ruby?

2 Answers2

6

Whichever reads cleaner is generally better. For example, if the string contains a number of variable references, each separated by a few characters, the "+" form of the expression can become complex and unclear, while an interpolated string is more obvious. On the other hand, if the expression(s) are relatively complex, it's better to separate them from other components of the string.

So, I think the following:

"Hello #{yourname}, my name is #{myname} and I'm #{mood} to see you."

is clearer than

"Hello " + yourname + ", my name is " + myname + " and I'm " + mood + "to see you."

But if I had complex expressions, I might want to separate those onto different source code lines, and those are better connected with "+".

djconnel
  • 441
  • 2
  • 4
  • 1
    These are good points. I will add that interpolation will implicitly wrap the expression being interpolated with a call to `#to_s`. So if the expression whose evaluation you want in your string does not evaluate to an instance of `String`, it will be cleaner to use interpolation rather than concatenation, to save yourself the explicit call to `#to_s`. – Gabe Kopley Jul 26 '12 at 00:27
2

I'm with @djconnel–use whichever reads the best, communicates the most information, eases modification and/or extension, makes debugging simple, and so on.

This was just discussed yesterday; see Strange Ruby Syntax?

In your specific example, I'd use string interpolation, because the method is really just:

def say_goodnight(name)
  "Good night, #{name.capitalize}"
end
Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302