views:

590

answers:

3

Hello,

I'm looking for a better way to merge variables in to a string, in Ruby.

For example if the string is something like:

"The animal action the *second_animal*"

And i have variables for Animal, Action and Second Animal, what is the prefered way to put those variables in to the string?

Thanks

James

+21  A: 

The idiomatic way is to write something like this:

"The #{animal} #{action} the #{second_animal}"
Mike Woodhouse
Sorry, maybe I simplified the problem too much. The String will be pulled from a database, and the variable dependant a number of factors. Normally I would use a replace for 1 or two varibles, but this has the potential to be more. Any thoughts?
FearMediocrity
The #{} construct is probably the fastest (although that still seems counterintuitive to me). As well as gix's suggestion, you can also assemble strings with + or <<, but there may be some intermediate strings created, which is costly.
Mike Woodhouse
+6  A: 

You can use sprintf-like formatting to inject values into the string. For that the string must include placeholders. Put your arguments into an array and use on of these ways: (For more info look at the documentation for Kernel::sprintf.)

fmt = 'The %s %s the %s'
res = fmt % [animal, action, other_animal]  # using %-operator
res = sprintf(fmt, animal, action, other_animal)  # call Kernel.sprintf

You can even explicitly specify the argument number and shuffle them around:

'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']
gix
+1  A: 

Consider an eRuby, erubis is good, or other templating system.

Logan Capaldo