I have this an array of hashes structured like this
[{:payer_id=>1, :price=>20}, {:payer_id=>2, :price=>30}] etc. How can I access the price given a specific payer_id? I know this question is basic but I can't figure it out.
You can do this
payers = [{:payer_id=>1, :price=>20}, {:payer_id=>2, :price=>30}] payer_id = 2 payers.detect { |payer| payer[:payer_id] == payer_id }.try(:[], :price) # => 30 I used detect to get the first payer that matches the id, then get its price. In case, no payer matched, you got nil returned so you can use try to get the price so the code won't raise errors even no payer were found.
※ try is part of ActiveSupport so if you don't use it, just replace .try(:[], :price) with [:price].
try requires ActiveSupport, which the OP may not have.#try method, you rid your code of chicken typing smell.