Skip to content

Instantly share code, notes, and snippets.

@cbilgili
Created June 19, 2013 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbilgili/5813063 to your computer and use it in GitHub Desktop.
Save cbilgili/5813063 to your computer and use it in GitHub Desktop.
Ruby string merge sprintf
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