Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search if a value exists in a Ruby Array

Tags:

arrays

ruby

I currently have this:

cart = [{"40"=>[{"size"=>"1", "count"=>1, "variation"=>nil, "style"=>"3"}]}, {"40"=>[{"size"=>"2", "count"=>1, "variation"=>nil, "style"=>"3"}]}]

How do I search this array and find out if "40" exists?

like image 688
Teej Avatar asked Aug 24 '26 20:08

Teej


1 Answers

Use Enumerable#any:

item_in_cart = cart.any? { |item| item.has_key?("40") } 
#=> true / false
like image 125
tokland Avatar answered Aug 27 '26 15:08

tokland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!