First of all, you can use find
instead of select
since you only want the first match. If you want a one-liner, you can do something like this:
(items.find { |key| key[:user] == 8 } || { :amount => 0 })[:amount]
If you happen to have Rails or ActiveSupport kicking around then you could use try
and to_i
(while remembering that nil.to_i == 0
) like this:
items.find { |k| key[:user] == 1 }.try(:fetch, :amount).to_i
try
just calls a method (fetch
in this case) but always returns nil
if the receiver is nil
so nil.try(:fetch, :amount)
is nil
but some_hash.try(:fetch, :amount)
is some_hash.fetch(:amount)
, it is a handy tool for swallowing up nil
s without adding a bunch of extra conditionals. AFAIK, the andand
gem does similar things without requiring all the ActiveSupport.