2

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.

1 Answer 1

4

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].

Sign up to request clarification or add additional context in comments.

2 Comments

Note that try requires ActiveSupport, which the OP may not have.
@oldergod: After the last edit I'm satisfied with the answer enough for an upvote. By ridding of #try method, you rid your code of chicken typing smell.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.