Ruby: Easiest Way to Filter Hash Keys?

前端 未结 13 1206

I have a hash that looks something like this:

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


        
13条回答
  •  我在风中等你
    2020-11-30 18:28

    Put this in an initializer

    class Hash
      def filter(*args)
        return nil if args.try(:empty?)
        if args.size == 1
          args[0] = args[0].to_s if args[0].is_a?(Symbol)
          self.select {|key| key.to_s.match(args.first) }
        else
          self.select {|key| args.include?(key)}
        end
      end
    end
    

    Then you can do

    {a: "1", b: "b", c: "c", d: "d"}.filter(:a, :b) # =>  {a: "1", b: "b"}
    

    or

    {a: "1", b: "b", c: "c", d: "d"}.filter(/^a/)  # =>  {a: "1"}
    

提交回复
热议问题