4 ms·
# bad email_with_name = user.name + ' <' + user.email + '>' # good email_with_name = "#{user.name} <#{user.email}>" # better email_with_name = "%s <
by mildavw 15y ago
# bad
email_with_name = user.name + ' <' + user.email + '>'
# good
email_with_name = "#{user.name} <#{user.email}>"
# better
email_with_name = "%s <%s>" % [user.name, user.email]
- sanderjd 15y agoWhy is the latter better? It seems equally good, but less idiomatic and certainly less obvious to most Ruby programmers.
- gioele 15y agoThe structure of strings like email_with_name = "%s <%s>" % [user.name, user.email] can be easily identified even when many fields are added. On the contrary, strings like email_with_name = "#{user.name} <#{user.email}>" become quite cramped as soon as you use three or more fields.
- sanderjd 15y agoI'm not sure what you mean by cramped, but I think that the interpolation style is, on the contrary, much easier to read when you have multiple fields: puts "#{num} #{vessels} of #{liquid} on the #{where}, you #{verb1} one #{adverb1}, #{verb2} it #{adverb2}, #{num - 1} #{vessels} of #{liquid} on the #{where}" puts "%d %s of %s on the %s, you %s one %s, %s it %s, %i %s of %s on the %s", [ num, vessels, liquid, where, verb1, adverb1, verb2, adverb2, num - 1 ] It's an extreme example, but you just read the first, while you have to think about the second.