Ruby: Easiest Way to Filter Hash Keys?

前端 未结 13 1190

I have a hash that looks something like this:

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


        
相关标签:
13条回答
  • 2020-11-30 18:53

    The easiest way is to include the gem 'activesupport' (or gem 'active_support').

    Then, in your class you only need to

    require 'active_support/core_ext/hash/slice'
    

    and to call

    params.slice(:choice1, :choice2, :choice3) # => {:choice1=>"Oh look, another one", :choice2=>"Even more strings", :choice3=>"But wait"}
    

    I believe it's not worth it to be declaring other functions that may have bugs, and it's better to use a method that has been tweaked during last few years.

    0 讨论(0)
提交回复
热议问题