简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM