Ruby: Easiest Way to Filter Hash Keys?

前端 未结 13 1202

I have a hash that looks something like this:

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


        
13条回答
  •  爱一瞬间的悲伤
    2020-11-30 18:29

    If you work with rails and you have the keys in a separate list, you can use the * notation:

    keys = [:foo, :bar]
    hash1 = {foo: 1, bar:2, baz: 3}
    hash2 = hash1.slice(*keys)
    => {foo: 1, bar:2}
    

    As other answers stated, you can also use slice! to modify the hash in place (and return the erased key/values).

提交回复
热议问题