Ruby: Merging variables in to a string

前端 未结 7 964
[愿得一人]
[愿得一人] 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条回答
  •  萌比男神i
    2020-12-02 10:36

    The standard ERB templating system may work for your scenario.

    def merge_into_string(animal, second_animal, action)
      template = 'The <%=animal%> <%=action%> the <%=second_animal%>'
      ERB.new(template).result(binding)
    end
    
    merge_into_string('tiger', 'deer', 'eats')
    => "The tiger eats the deer"
    
    merge_into_string('bird', 'worm', 'finds')
    => "The bird finds the worm"
    

提交回复
热议问题