Jor*_*tos 2 ruby hash ruby-on-rails-3 ruby-on-rails-4
如何通过数组为 ruby 中的散列创建一个切片,如下所示:
info = { :key1 => "Lorem", :key2 => "something...", :key3 => "Ipsum" }
needed_keys = [:key1, :key3]
info = info.slice( needed_keys )
Run Code Online (Sandbox Code Playgroud)
我想收到:
{ :key1 => "Lorem", :key3 => "Ipsum" }
Run Code Online (Sandbox Code Playgroud)
的ActiveSupport的Hash#slice不带钥匙作为参数数组,你必须通过你想提取单参数,例如按键泼洒您的needed_keys数组:
info.slice(:key1, :key3)
# => {:key1=>"Lorem", :key3=>"Ipsum"}
info.slice(*needed_keys)
# => {:key1=>"Lorem", :key3=>"Ipsum"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1354 次 |
| 最近记录: |