Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Multiple Values From Hash In Very Efficient Way

Tags:

ruby

hash

My code is

a={"1"=>"adi","2"=>"amar","3"=>"rave","4"=>"sum"}
arr=["1","5","3"]

I want to extract all values like this if array values exist in the hash

result =["adi","rave"]

without using any loop.Is it possible

like image 624
Ravendra Kumar Avatar asked Jul 10 '13 09:07

Ravendra Kumar


People also ask

Can a hash key have multiple values?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

Can a Key have multiple values Ruby?

Multiple Values For One Key Words are unique, but they can have multiple values (definitions) associated with them. You can do this in Ruby!

What is a hash pair?

Entries in a hash are often referred to as key-value pairs. This creates an associative representation of data. Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated.

Are Ruby hashes ordered?

Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.


1 Answers

You could do:

a.values_at(*arr).compact
# => ["adi", "rave"] 
like image 102
toro2k Avatar answered Sep 23 '22 15:09

toro2k