diff --git a/README.md b/README.md index f2dd092..d00d37e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1399 TILs and counting..._ +_1400 TILs and counting..._ --- @@ -1129,6 +1129,7 @@ _1399 TILs and counting..._ - [Fetch Warns About Superseding Block Argument](ruby/fetch-warns-about-superseding-block-argument.md) - [Find The Min And Max With A Single Call](ruby/find-the-min-and-max-with-a-single-call.md) - [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md) +- [Format A Hash Into A String Template](ruby/format-a-hash-into-a-string-template.md) - [Generate A Signed JWT Token](ruby/generate-a-signed-jwt-token.md) - [Generate Ruby Version And Gemset Files With RVM](ruby/generate-ruby-version-and-gemset-files-with-rvm.md) - [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md) diff --git a/ruby/format-a-hash-into-a-string-template.md b/ruby/format-a-hash-into-a-string-template.md new file mode 100644 index 0000000..045d3d8 --- /dev/null +++ b/ruby/format-a-hash-into-a-string-template.md @@ -0,0 +1,35 @@ +# Format A Hash Into A String Template + +The `%` method as defined by `String` +([`String#%`](https://ruby-doc.org/core-3.0.0/String.html#method-i-25)) allows +you to format (interpolate) an object or array of values into a string. That +string needs to contain template markers for where the values should go. + +Here is an example of folding an array of values into a string with [`%s` +format +specifier](https://docs.ruby-lang.org/en/master/format_specifications_rdoc.html#label-Specifier+s): + +```ruby +> User = Struct.new(:id) +=> User +> user1 = User.new(123) +=> # +> "%s ID: %s" % [user1.class.to_s, user1.id] +=> "User ID: 123" +``` + +Or perhaps more usefully for a string that acts as a template, you can used +named specifiers that correspond to hash keys: + +```ruby +> template = "You paid %{formatted_price} for %{product}. Enjoy your purchase!" +=> "You paid %{formatted_price} for %{product}. Enjoy your purchase!" + +> data = { product: "Ruby Explained™", formatted_price: "$38.99" } +=> {:product=>"Ruby Explained™", :formatted_price=>"$38.99"} + +> template % data +=> "You paid $38.99 for Ruby Explained™. Enjoy your purchase!" +``` + +[source](https://hashrocket.com/blog/posts/using-a-hash-of-data-for-string-replacement-in-ruby)