16
14

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 5 years have passed since last update.

[Ruby]gsubにhashを渡す

Posted at

1.9.3からgsubの第二引数にhashを渡せるようになっていたことを今日知りました。
gsubのマニュアル

時々erbを使うほどでも無いテンプレートの変数置換で

replace_hash = {
  "#to#"   => "taro",
  "#from#" => "jiro"
}

template = <<EOS
hello, #to#.
message from #from#.
EOS

というのがある場合、

puts template.gsub(/#.*#/) {|matched|
  replace_hash[matched]
}
#=>hello, taro.
#  message from jiro.

というようなコードをよく書いていたのですが、これが単純に

puts template.gsub(/#.*#/, replace_hash)
#=>hello, taro.
#  message from jiro.

これで、同じことができます。

やっぱりマニュアルは日頃からよく読んでおかないといけませんね。

16
14
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
16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?