Subselecting hash back into hash (oneliner?)

J

Jon Baer

Going through pick-axe and was just wondering if there was a one
liner for something such as this that I may have missed:

h2 = Hash.new
h1 = {"foo1"=>"bar1", "foo2"=>"bar2"}
query = h1.select { |k,v| v == "bar2" }
query.each do |result|
h2[result[0]] = result[1]
end
p h2

Thanks.

- Jon
 
J

James Edward Gray II

Going through pick-axe and was just wondering if there was a one
liner for something such as this that I may have missed:

h2 = Hash.new
h1 = {"foo1"=>"bar1", "foo2"=>"bar2"}
query = h1.select { |k,v| v == "bar2" }
query.each do |result|
h2[result[0]] = result[1]
end
p h2

Like this?
h1 = {"foo1"=>"bar1", "foo2"=>"bar2"} => {"foo1"=>"bar1", "foo2"=>"bar2"}
h2 = Hash[*h1.select { |k, v| v == "bar2" }.flatten]
=> {"foo2"=>"bar2"}

Hope that helps.

James Edward Gray II
 
J

Jon Baer

Nice .. well that works :) but in the constructor can you tell me
what "*" would literally "mean"?

Does this just take only an Array obj or could you place any object
in there w/ public attributes/methods?

(Was this covered in pick-axe somewhere I missed?)

Thank you, much appreciated ...

- Jon

h1 = {"foo1"=>"bar1", "foo2"=>"bar2"} => {"foo1"=>"bar1", "foo2"=>"bar2"}
h2 = Hash[*h1.select { |k, v| v == "bar2" }.flatten]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top