Read more

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

Felix Eschey
November 23, 2023Software engineer at makandra GmbH

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"
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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' }
Posted by Felix Eschey to makandra dev (2023-11-23 19:14)