Reputation: 550
I am populating an array of hashes from the database and what I get in the end looks like:
[{:element1 => "value1", :element2 => "value2"}, {:element1 => "value3", :element2 => "value4"}]
What I want to do now is write the value of element2 if element1 has value1. I tried doing
puts my_array[my_array.index(:element1 => "value1")].element2
but that only gives me an error saying:
no implicit conversion from nil to integer
What I am using now is
puts my_array.find_by_element1("value1").element2
but that queries the database every time and I would like to avoid that if possible since I already have all the values.
Edit: my Ruby version is 1.8.7
Upvotes: 0
Views: 1927
Reputation: 6803
result = [{:element1 => "value1", :element2 => "value2"}, {:element1 => "value3", :element2 => "value4"}]
result.each do |x|
puts "#{x[:element2]}" if x[:element1]=="value1"
end
Upvotes: 2
Reputation: 222398
You can't use index
for partial matches. Try using detect
.
my_array.detect { |el| el[:element1] == "value1" }[:element2]
=> "value2"
Upvotes: 2