I am beginning to adventure in Ruby and I need to find in this array of
hashes the id with the value of 3 and get its price. What would be the
easiest way to do it?
I am beginning to adventure in Ruby and I need to find in this array of
hashes the id with the value of 3 and get its price. What would be the
easiest way to do it?
I am beginning to adventure in Ruby and I need to find in this array of
hashes the id with the value of 3 and get its price. What would be the
easiest way to do it?
I tried your code but I keep getting nil, but I know for sure that the
value "3" is in there.
sql = "SELECT p.id, s.price FROM services s inner join products as p
ON s.product_id = p.id where s.shop_id = 1"
r = ActiveRecord::Base.connection.select_all(sql) @array = r.find {|k,v| k[:id] == "3"}
if I change it to @array = r.find {|k,v| v[:id] == "3"}
I get
undefined method `[]' for nil:NilClass
That's because you need to put your array in a comma separated list of values inside :
irb(main):026:0> array = [{ :id => 1, :price => 0.25 },
irb(main):027:1* { :id => 2, :price => 0.35 },
irb(main):028:1* { :id => 3, :price => 0.25 }]
=> [{:id=>1, :price=>0.25}, {:id=>2, :price=>0.35}, {:id=>3, :price=>0.25}]
Now that we have an array, we can find the element with the id of 3 like so:
irb(main):029:0> item = array.find {|hash| hash[:id] == 3 }
=> {:id=>3, :price=>0.25}
and get it's price:
irb(main):030:0> item[:price]
=> 0.25
Hopefully that helps.
Walton
···
On 6/28/2013 5:58 PM, Rodrigo Lueneberg wrote:
I am sorry, I did not understand what you tried to convey. To me it is
clear that is an array of hashes. I just don't get your example..
And remember: the more precise the information you give, the better
we can help. Generally, it's good practice to make extensive use
of 'irb' for experimenting/debugging, and often it's also helpful
to include some 'puts myvar', or 'p myvar' statements in the code,
to see what is actually going on.
Have fun hacking Ruby,
Marcus
···
Am 30.06.2013 17:34, schrieb Rodrigo Lueneberg:
Sorry guys for not Copyind and Pasting. But at the same time I am so
happy that I found a place where people really help each other. Thank
you