Ruby: Easiest Way to Filter Hash Keys?

前端 未结 13 1210

I have a hash that looks something like this:

params = { :irrelevant => \"A String\",
           :choice1 => \"Oh look, another one\",
           :choi         


        
13条回答
  •  醉酒成梦
    2020-11-30 18:38

    In Ruby, the Hash#select is a right option. If you work with Rails, you can use Hash#slice and Hash#slice!. e.g. (rails 3.2.13)

    h1 = {:a => 1, :b => 2, :c => 3, :d => 4}
    
    h1.slice(:a, :b)         # return {:a=>1, :b=>2}, but h1 is not changed
    
    h2 = h1.slice!(:a, :b)   # h1 = {:a=>1, :b=>2}, h2 = {:c => 3, :d => 4}
    

提交回复
热议问题