Created
June 19, 2013 09:44
-
-
Save cbilgili/5813063 to your computer and use it in GitHub Desktop.
Ruby string merge sprintf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'] | |
Or specify the argument using hash keys: | |
'The %{animal} %{action} the %{second_animal}' % | |
{animal: 'cat', action: 'eats', second_animal: 'mouse'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment