Ruby: Using `sprintf` to replace a string at fixed named references

Updated . Posted . Visible to the public.

The sprintf method Show archive.org snapshot has a reference by name Show archive.org snapshot format option:

sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 }) # => 1 : 2.000000
sprintf("%{foo}f", { :foo => 1 })                      # => "1f"

The format identifier %<id> stands for different data types to be formatted, such as %f for floats:

sprintf('%f', 1) # => 1.000000

Example:

This is quite useful to replace long strings such as API endpoints which might take several parameters.

In this example we are using %s identifier to replace strings.

class Fetcher
  FIND_URI = 'https://someapi.com/3/search/record?query=%<search_word>s&include_many=%<include_many>s&language=en-US&page=1'
  
  # some public methods 
  
  private
  
  def find_endpoint
    format(FIND_URI, { search_word: @record.name, include_many: 'false' })
  end
end

Note that the example uses the format-alias for sprintf since it makes semantically more sense within this context.

On Strings you can also use the method % instead of format or sprintf.

FIND_URI % { search_word: @record.name, include_many: 'false' }
Felix Eschey
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Felix Eschey to makandra dev (2023-11-23 18:14)