Ruby如何获得部分哈希

时间:2014-02-16 20:44:14

标签: ruby-on-rails

如果我有像这样的红宝石哈希,

first = {:a => 1,:b => 2,:c => 3,:d => 4,:e => 5}

如何通过单行脚本

实现这一目标

second = {:a => 1,:c => 3,:e => 5}

非常感谢你。

5 个答案:

答案 0 :(得分:2)

你想要的是一个漂亮的代码行

second = first.slice(:a, :c, :e) # => {:a=>1, :c=>3, :e=>5}

编辑:之前的回答是使用Rails。这是一个使用Ruby的解决方案

second = first.delete_if {|k,v| ![:a, :c, :e].include?(k) } # => {:a=>1, :c=>3, :e=>5}

答案 1 :(得分:2)

first.keep_if {|键| [:一,:C,:d] .INCLUDE(键)}

答案 2 :(得分:2)

尝试delete_ifkeep_if,它们都是Ruby核心的一部分。它们都在当前哈希上操作。 slice也已经是核心Ruby的一部分。

first =  {:a=>1,:b=>2,:c=>3,:d=>4,:e=>5}
first_clone = first.clone
p first.keep_if { |key| [:a, :c, :e].include?(key) } # =>  {:a=>1,:c=>3,:e=>5}
p first_clone.delete_if { |key, value| [:b, :d, :f].include?(key) } # =>  {:a=>1,:c=>3,:e=>5}

文档:

答案 3 :(得分:0)

方法1

first = {:a=>1,:b=>2,:c=>3,:d=>4,:e=>5}
first.delete(:b)
first.delete(:d)
second = first

方法2

first = {:a=>1,:b=>2,:c=>3,:d=>4,:e=>5}
second = first.delete_if {|key, value| key == :b || key == :d }

答案 4 :(得分:0)

假设您不知道要保留/删除的密钥......您可以这样做:

first = {:a=>1,:b=>2,:c=>3,:d=>4,:e=>5}
iterator = 0
second = {}
first.each_pair do |key, value|
  second[key] = value if iterator % 2 == 0
  iterator += 1
end

second # is now {:a=>1,:c=>3,:e=>5}