开发者

Search if a value exists in a Ruby Array

开发者 https://www.devze.com 2023-03-06 12:20 出处:网络
I currently have this: cart = [{\"40\"=>[{\"size\"=>\"1\", \"count\"=>1, \"variation\"=>nil, \"style\"=>\"3\"}]}, {\"40\"=>[{\"siz开发者_如何学Ce\"=>\"2\", \"count\"=>1, \"var

I currently have this:

cart = [{"40"=>[{"size"=>"1", "count"=>1, "variation"=>nil, "style"=>"3"}]}, {"40"=>[{"siz开发者_如何学Ce"=>"2", "count"=>1, "variation"=>nil, "style"=>"3"}]}]

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


Use Enumerable#any:

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消