ruby - Return 0 when select returns nothing? -


Say I have an array of palm like:

  items = [[: User = & gt; 1,: zodiac = & gt; 484}, {: user = & gt; 2 ,: zodiac => 0}, {: user = & gt; 3 ,: zodiac = & gt; 8633}]   

To get the amount for a user, I want something like this:

  items.select { | Key | Key [: User] == 1}.   

But if there is no ID then is not user , then it will not work:

  & Gt; Items.select {| Key | Key [: user] == 8}. First [: amount] # no methoder: Undefined method for zero, `]]: NilClass   

how can I return the amount if it finds the item , But 0 is nothing back then

First of all, Instead you can use it because you want only the first match if you want the one-liner, then you can do something like this:

  (items.find {| key | key [: user ] == 8} || {: zodiac => if you kick around Rails or ActiveSupport You can use it and  to_i  (while  remembering zero) 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 zero if the receiver is zero then is nil.try (: fetch, zodiac) nothing but some_hash.try (: fetch, amount) is some_hash.fetch (amount) , it's an easy tool to swallow < Without needing to add a bunch of code> Zero s. AFAIK, andand gem is required for all ActiveSupport Does the same things without.

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -