Rubyの`Enumerable#each_with_object`を使ってみた
attr_accessor
で生やしたattributes達とそのvaluesをハッシュとして欲しいことがあり、最初はこんな感じに書いた。
hoge_attributes = {} %I(user_name first_name last_name email).each do |attr| hoge_attributes[attr] = @hoge.send(attr) end
次の日に、電車の中で『パーフェクトRuby』を読んでいたら、もっと短くかけそうな書き方が書いてあった。
Enumerable#each_with_object
そいつを使えばこんな感じに書き換えららそう。
hoge_attributes = %I(user_name first_name last_name email).each_with_object({}) do |attr| hoge_attributes[attr] = @hoge.send(attr) end
実際バイト数は増えたが、行数は減った。 勉強になった。
- 作者: Rubyサポーターズ,すがわらまさのり,寺田玄太郎,三村益隆,近藤宇智朗,橋立友宏,関口亮一
- 出版社/メーカー: 技術評論社
- 発売日: 2013/08/10
- メディア: 大型本
- この商品を含むブログ (12件) を見る