1 min read

TIL: Complex String Interpolation with Ruby

Another one I re-remembered recently and prefer for complex string interpolations

Another one I re-remembered recently and prefer for complex string interpolations.

I find myself doing things like this a lot

uri = "#{Settings.service.scheme}://#{Settings.service.host}:#{port}/#{Settings.service.base_path}#{Settings.service.endpoint}"

This is ugly and hard to read. Then I remembered the String#% method.

uri = '%s://%s:%s/%s%s' % [Settings.service.scheme,
                           Settings.service.host,
                           Settings.service.port,
                           Settings.service.base_path,
                           Settings.service.endpoint]

Better in that I can see the variables I'm inserting more easily but that pattern string is gross. (I also like that I can use single-quoted strings but I know there's hating on this.) Let's improve this some more.

uri = '%<scheme>s://%<host>s:%<port>s/%<base>s%<endpoint>s' % {
  scheme:   Settings.service.scheme,
  host:     Settings.service.host,
  port:     Settings.service.port,
  base:     Settings.service.base_path,
  endpoint: Settings.service.endpoint
}

Much clearer with the added benefit of being able to use all the power of Ruby's string formatters.