Ruby: Merging variables in to a string

前端 未结 7 987
[愿得一人]
[愿得一人] 2020-12-02 10:23

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

For example if the string is something like:

\"The animal action<

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 10:38

    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'}
    

    Note that you must provide a value for all arguments to the % operator. For instance, you cannot avoid defining animal.

提交回复
热议问题