Teej
Teej

Reputation: 12891

Search if a value exists in a Ruby Array

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?

Upvotes: 2

Views: 2780

Answers (3)

tokland
tokland

Reputation: 67910

Use Enumerable#any:

item_in_cart = cart.any? { |item| item.has_key?("40") } 
#=> true / false

Upvotes: 9

Michael De Silva
Michael De Silva

Reputation: 3818

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" }

Upvotes: 2

Doug R
Doug R

Reputation: 5779

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")}

Upvotes: 7

Related Questions