2

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?

2
  • 3
    Exists in what way? Technically speaking, '40' is not a member of your array. Commented May 16, 2011 at 15:57
  • cart[0].first[0] == "40" now build that into a cart.each block. I guess he's referring to the string-key "40". Commented May 16, 2011 at 15:58

3 Answers 3

9

Use Enumerable#any:

item_in_cart = cart.any? { |item| item.has_key?("40") } #=> true / false 
Sign up to request clarification or add additional context in comments.

Comments

7

If you want to find if "40" is a key in any of your array items, you can do:

cart.detect{|i| i.has_key?("40")} 

Comments

2

You can also do

cart.each do |c| if c.first[0] == "40" match = true end end 

or far cleaner

match = cart.any? {|c| c.first[0] == "40" } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.