Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1rubygems

When Should I use expression interpolation in Ruby?


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?


Solution

  • 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 "+".