简体   繁体   中英

Accessing entire hash in context inside block

Say I have this hash:

hash = { :c => "three", :a => "one", :b => "two" }

And I want to have this at the end:

one, two, three

Now say that this is well nested inside a different hash. I want to avoid things like:

puts "#{bigger_hash[0].hash[:a]}, #{bigger_hash[0].hash[:b]}, #{bigger_hash[0].hash[:c]}"

I know there's this form for map which lets me do something like this without defining the order:

bigger_hash[0].hash.map{|k,v| v}.join(', ')

Which will output:

three, one, two

Which removes flexibility. I want to explicitly address these in the order I want (not necessarily numerical or alphabetical!)

Is there a convenience method I can use to achieve this? I was thinking something along the lines of:

bigger_hash[0].hash.magic{"#{a}, #{b} #{c}"}
# or
bigger_hash[9].hash.magic(:a, :b, :c).join(', ')

也许这是你的ans:

bigger_hash[9].hash.values_at(:a, :b, :c).join(', ')

what is bigger_hash returns? I am not sure what you are looking for but as I understood you want to sort your hash by keys and return it's values . Check this:

> hash = { :c => "three", :a => "one", :b => "two" }
> hash.sort.map{|e| e[1] }.join(' , ')
 => "one , two , three"  # your expected output

OR

> hash.values_at(:a, :b, :c).join(', ')
=> "one, two, three"

You can also use this type:

hash = { :c => "three", :a => "one", :b => "two" }
Hash[hash.sort].values.join(", ")
# => "one, two, three"

But map method is better in this case.

First of all, one should define the sorting function:

sorter = lambda { |o1, o2| o1 <=> o2 }

Then you are able to get values sorted as you wanted:

hash = { :c => "three", :a => "one", :b => "two" }
hash.sort(&sorter).to_h.values.join(', ')
#⇒ one, two, three

Eg for reverse order we get:

sorter = lambda { |o1, o2| o2 <=> o1 }
hash.sort(&sorter).to_h.values.join(', ')
#⇒ three, two, one

Legacy rubies don't have #to_h method:

hash.sort(&sorter).map(&:last).join(', ')

Inplace sorter:

hash.sort(&lambda{ |o1,o2| o1 <=> o2 }).map(&:last).join(', ')
#⇒ "one, two, three"

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM