0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby - Hash を使った文字列のフォーマット

Last updated at Posted at 2022-02-17

Ruby のコードをレビューしてるときに、文字列とHashを演算子で処理しているコードに出会い、意味が理解できなくて苦労した。
具体的にはこんなコード。

$my_preference = {
    "seafood".to_sym => "salmon"
}

my_cheese = "I love %{cheese} cheese."
my_cheese %= $my_preference

おそらく、この X %= BX = X % B の代入演算子なんだろうけど、それでは % は何をするのかと思って調べた。
この場合、Xは文字列でBはHashなので、当然ながら整数除算の「あまり」の計算じゃないし…、Ruby って不思議すぎと思ったら、Help and documentation for the Ruby programming language.Class: String - str % arg → new_strに説明がありました。
%{}で囲まれた文字列をキーとしてHashから取り出した値で、%{から}を置き換えてくれるようです。
以下にサンプルコードと出力内容を付けます。

$my_preference = {
    "meet".to_sym => "pork",
    "seafood".to_sym => "salmon",
    "vegitable".to_sym => "cucumber",
    "fruite".to_sym => "strawberry",
    "cheese".to_sym => "cheddar"
}

seafood_tmpl = "My favolit seafood is %{seafood}."
puts seafood_tmpl #=> My favolit seafood is %{seafood}.

my_seafood = seafood_tmpl % $my_preference
puts my_seafood #=> My favolit seafood is salmon.

my_cheese = "I love %{cheese} cheese."
puts my_cheese  #=> I love %{cheese} cheese.

my_cheese %= $my_preference
puts my_cheese  #=> I love cheddar cheese.

便利です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?