5

This has been bugging me for a while. It's not a difficult thing, but I don't know why there's no easy way to do it already, and I bet there is and I don't see it.

I just want to take a hash, like this:

cars = {:bob => 'Pontiac', :fred => 'Chrysler', 
        :lisa => 'Cadillac', :mary => 'Jaguar'}

and do something like

cars[:bob, :lisa]

and get

{:bob => 'Pontiac', :lisa => 'Cadillac'}

I did this, which works fine:

class Hash
  def pick(*keys)
    Hash[select { |k, v| keys.include?(k) }]
  end
end

ruby-1.8.7-p249 :008 > cars.pick(:bob, :lisa)
=> {:bob=>"Pontiac", :lisa=>"Cadillac"} 

There's obviously a zillion easy ways to do this, but I'm wondering if there's something built in I've missed, or a good an un-obvious reason it's not a standard and normal thing? Without it, I wind up using something like:

chosen_cars = {:bob => cars[:bob], :lisa => cars[:lisa]}

which isn't the end of the world, but it's not very pretty. It seems like this should be part of the regular vocabulary. What am I missing here?

(related questions, include this: Ruby Hash Whitelist Filter) (this blog post has precisely the same result as me, but again, why isn't this built in? http://matthewbass.com/2008/06/26/picking-values-from-ruby-hashes/ )

update:

I'm using Rails, which has ActiveSupport::CoreExtensions::Hash::Slice, which works exactly as I want it to, so problem solved, but still... maybe someone else will find their answer here :)

3
  • It doesn't seem to be built-in and I don't think this is the right place to ask why.
    – Mischa
    Feb 9, 2012 at 7:29
  • I thought about deleting the question once I found ActiveSupport::CoreExtensions::Hash::Slice, but I figure Stack Overflow is a resource for finding answers, and I would have found it faster if this question had already been here. Feb 9, 2012 at 9:36
  • I guess your question is valid and this is just a technicality, but you'd better ask how to do something, not why something is not available.
    – Mischa
    Feb 9, 2012 at 9:46

5 Answers 5

7

Just to help others, some years after the fact:

Slice works nicely to do what I wanted.

> cars.slice(:bob, :lisa)
=> {:bob=>"Pontiac", :lisa=>"Cadillac"} 
2
  • 1
    Hash#slice is a recent addition to Hash, used to be only available as part of ActiveSupport in Rails but became part of the Ruby core in 2.5.0. Jul 24, 2018 at 21:50
  • Yup. I figure anyone having this problem now should see the latest answer. Jul 25, 2018 at 3:40
4

I've always thought that was a weird omission as well, but there really is no simple, standard method for that.

Your example above might be unnecessarily slow because it iterates over all the hash entries whether we need them or not, and then repeatedly searches through the keys parameter array. This code should be a bit faster (assuming that would ever matter -- and I haven't tried to benchmark it).

class Hash
  def pick(*keys)
    values = values_at(*keys)
    Hash[keys.zip(values)]
  end
end
7
  • my instinct is that since your solution looks up by value instead of key, it would probably benchmark the same or slower, but at least for most applications, I'm pretty sure it won't make any material difference. Feb 9, 2012 at 9:40
  • 2
    Hash[keys.zip(values)] is probably a bit faster with the same result Feb 9, 2012 at 11:59
  • 1
    @stephan-com, values_at looks up a value for each key, and returns and array of values in the same order. There are no lookups being done by value. Feb 9, 2012 at 14:29
  • @victor-moroz, I had not known that a single array argument could be passed to Hash.[], and it would seem likely that's faster than passing the array as arguments. I ran a benchmark, however, and found that passing as arguments is more than twice as fast under ruby 1.8.7-p302. p=[1,2,3,4,5,6,7,8,9,10]; Benchmark.measure{ 100000.times{ Hash[p] } } gives ...@real=0.762746095657349, @utime=0.72..., and the same test using Hash[*p] gives ,,,@real=0.325729131698608, @utime=0.279999999999999.... I'm not at all sure what would account for that large difference, however. Feb 14, 2012 at 7:22
  • Curious about the big performance discrepancy, I browsed to apidock.com/ruby/v1_8_7_330/Hash/%5B%5D/class, and clicked the Show Source link. Apparently, when *array is passed, Ruby converts this to a C array & argc, then Hash.[] simply iterates the pairs, and sets each k/v. When a single array argument is passed, however, Hash[] must first try coercing it to a Hash, then try coercing it to an Array, and then iterate/extract the elements (presumably just like Ruby otherwise does prior to invocation), and then iterates & inserts. The type checking/coercion looks like the performance hit. Feb 14, 2012 at 9:31
1

select deserves at least to be mentioned:

cars = {:bob => 'Pontiac', :fred => 'Chrysler', 
        :lisa => 'Cadillac', :mary => 'Jaguar'}
people = [:bob, :lisa]

p cars.select{|k, _| people.include?(k)}
#=> {:bob=>"Pontiac", :lisa=>"Cadillac"}
2
  • 1
    only works in ruby 1.9. ruby 1.8 will return an array ruby-doc.org/core-1.8.7/Hash.html#method-i-select
    – Luis R.
    Mar 30, 2012 at 1:33
  • Just so it's noted, you can get the same effect from select in 1.8 by surrounding the select call with Hash[], i.e., Hash[somehash.select{|k,v| /*some select criteria*/}]
    – A. Wilson
    Apr 26, 2013 at 21:11
0

Ruby makes it possible to add that feature without much pain:

class Hash
  alias old_accessor :[]

  def [](*key)
    key.is_a?(Array) ? self.dup.delete_if{|k, v| !key.include? k} : old_accessor(key)
  end
end

I hope this helps. I know it's not a built-in feature.

1
  • Any ideas on the pros/cons of using self.dup.delete_if over self.select?
    – A. Wilson
    Apr 26, 2013 at 21:12
0
{ height: '178cm', weight: '181lbs', salary: '$2/hour' }.select { |k,v| [:height, :weight].include?(k)  }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.