Ruby: Easiest Way to Filter Hash Keys?

前端 未结 13 1188

I have a hash that looks something like this:

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


        
13条回答
  •  [愿得一人]
    2020-11-30 18:44

    I had a similar problem, in my case the solution was a one liner which works even if the keys aren't symbols, but you need to have the criteria keys in an array

    criteria_array = [:choice1, :choice2]
    
    params.select { |k,v| criteria_array.include?(k) } #=> { :choice1 => "Oh look another one",
                                                             :choice2 => "Even more strings" }
    

    Another example

    criteria_array = [1, 2, 3]
    
    params = { 1 => "A String",
               17 => "Oh look, another one",
               25 => "Even more strings",
               49 => "But wait",
               105 => "The last string" }
    
    params.select { |k,v| criteria_array.include?(k) } #=> { 1 => "A String"}
    

提交回复
热议问题