Reputation: 5603
I have a hash like so:
hash = {"jonathan" => "12", "bob" => 15 }
Then I have an array like so:
array = ['jon', 'bob']
I want to return the value of the key that includes a value in my array in the end.
The goal is something like this:
array.each do |name|
if hash.key.include? name
return hash.value
end
What's the best way to write that code block?
Upvotes: 1
Views: 154
Reputation: 118271
Here is how I would write :
hash = {"jonathan" => "12", "bob" => 15 }
array = ['jon', 'bob']
array.collect(&hash.method(:[])).compact # => [15]
Upvotes: 0
Reputation: 16507
Also you can use select
methods of Hash
:
hash.select {| k,_ | array.include?( k ) }
# => {"bob"=>15}
and get, for example, last value:
hash.select {| k,_ | array.include?( k ) }.to_a.flatten.last
# => 15
or even use values_at
method of Hash
:
hash.values_at( *array ).compact.last
# => 15
Upvotes: 1
Reputation: 369054
If you want multiple values, use Hash#values_at
:
hash = {"jonathan" => "12", "bob" => 15 }
array = ['jon', 'bob']
hash.values_at(*array.select{|key| hash.has_key? key})
# => [15]
Using Array#&
:
hash.values_at(*(hash.keys & array))
# => [15]
Upvotes: 1
Reputation: 15515
To get the keys, you don't need a block, this will do:
hash.keys & array
This takes the keys of the hash and intersect it with the array.
Second part, get a value from the hash:
hash[(hash.keys & array).last]
This will get the last key that is shared in hash
and array
and returns the value of that key in hash
.
Upvotes: 1