params = {:aaa => "a", :bbb => "b", :ccc => "c", :ddd => "d"}
から
=> {:aaa=>"a", :bbb=>"b", :ccc=>"c"}
を生成する。
sample1.rb
params = {:aaa => "a", :bbb => "b", :ccc => "c", :ddd => "d"}
#1.
result_1 = {:aaa => params[:aaa], :bbb => params[:bbb], :ccc => params[:ccc]}
#2.
result_2 = {}
[:aaa, :bbb, :ccc].each{|k| result_2[k] = params[k]}
#3.
result_3 = [[:aaa, :bbb, :ccc], params.values_at(:aaa, :bbb, :ccc)].transpose.to_h
#4. Rails拡張
result_4 = params.slice(:aaa, :bbb, :ccc)
p result_1
p result_2
p result_3
p result_4
result1.
{:aaa=>"a", :bbb=>"b", :ccc=>"c"}
{:aaa=>"a", :bbb=>"b", :ccc=>"c"}
{:aaa=>"a", :bbb=>"b", :ccc=>"c"}
{:aaa=>"a", :bbb=>"b", :ccc=>"c"}
4.のみキーが存在しない際の動きが異なる。
sample2.rb
params = {:aaa => "a", :bbb => "b", :ccc => "c", :ddd => "d"}
#1.
result_1 = {:aaa => params[:aaa], :bbb => params[:bbb], :hoge => params[:hoge]}.
#2.
result_2 = {}
[:aaa, :bbb, :hoge].each{|k| result_2[k] = params[k]}
#3.
result_3 = [[:aaa, :bbb, :hoge], params.values_at(:aaa, :bbb, :hoge)].transpose.to_h
#4. Rails拡張
result_4 = params.slice(:aaa, :bbb, :hoge)
p result_1
p result_2
p result_3
p result_4
result2.
{:aaa=>"a", :bbb=>"b", :hoge=>nil}
{:aaa=>"a", :bbb=>"b", :hoge=>nil}
{:aaa=>"a", :bbb=>"b", :hoge=>nil}
{:aaa=>"a", :bbb=>"b"}
100000回実行時の処理速度
No. | time(s) |
---|---|
1 | 0.05948762223124504 |
2 | 0.08977324888110161 |
3 | 0.13127699121832848 |
4 | 0.19742310792207718 |