Search code examples
rubystringstring-substitution

How to use in Ruby variable arguments with "#{...}?


I want to have a method like this:

def process(text, *parameters)
   new_text = ...
end

where calling the function with

process("#{a} is not #{b}", 1, 2)

resulting in new_text being 1 is not 2 and calling the function with

process("#{a} does not exist", 'x')

resulting in new_text being x does not exist.

Or using an alternative way instead of using "#{...}" (e.g. #1, #2) to pass a string for arguments which are filled in/substituted.


Solution

  • You can to something like this:

    def format(text, *args)
      text % args
    end
    
    format("%s is not %s", 1, 2)
    # => "1 is not 2"
    
    format("%s does not exist", 'x')
    # => "x does not exist"
    

    See String#% and Kernel#sprintf

    Because the above method uses String#% internally it is actually shorter to use String#% directly then wrapping it into another method:

    "%s is not %s" % [1, 2]
    # => "1 is not 2"
    
    "%s does not exist" % 'x'
    # => "x does not exist"
    

    Note that multiple arguments must be passed in as an array in this example.