1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-04 23:58:01 +00:00

Add Format A Hash Into A String Template as a Ruby TIL

This commit is contained in:
jbranchaud
2024-03-18 09:34:06 -05:00
parent b6e5ea4c03
commit 6096f5af10
2 changed files with 37 additions and 1 deletions

View File

@@ -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)

View File

@@ -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)
=> #<struct User id=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)