How to Use Format Specifiers With Named Parameters in a Ruby String?

To format a named parameter in Ruby, you will have to use %<name> style instead of %{name} style (as the latter does not support formatting). You can then append the format specifier prefixed with a dot (.) to the named parameter to format it. For example:

puts "%<num>.d equals to %<num>.x in hexadecimal" % {num: 28}

# output: "28 equals to 1c in hexadecimal"

As you can see in the code above, the .d format specifies that the variable should be interpreted as a decimal number and .x format specifies that the variable should be interpreted as a hexadecimal number.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.