100
93

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.

Hash#map は Hash を返さない

Last updated at Posted at 2013-02-04

ごく当たり前の話だとは思うのですけど、メモ。

h = { :hoge => 'hoge', :fuga => 'fuga' }
h.map { |k, v| v.upcase } # ["HOGE", "FUGA"] 

HashにしたければHashに突っ込んでやればよい。

Hash[h.map { |k,v| [k,v.upcase] }] # {:hoge=>"HOGE", :fuga=>"FUGA"} 

速度の計測したわけじゃないし普通はどんなやり方するのかわかんないけど、
とりあえずこれで解決した。

追記
会社の人に話を聞いてみると、Nabetaniさんが提示してくださった

def f(x); "SomeCalc[%s]"%x ; end
result = h.inject( {} ){ |a,(k,v)| a[k]=f(v);a } 
# {:hoge=>"SomeCalc[HOGE]", :fuga=>"SomeCalc[FUGA]"}

が一般的らしいです。

追記
Ruby2.1以降、Array#to_hが追加されました。

result = h.map { |k,v| [k,v.upcase] }.to_h
# {:hoge=>"HOGE", :fuga=>"FUGA"}

空のHashにinjectしていくよりも読みやすいと思います。

100
93
5

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
100
93

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?