Vlad Cenan Vlad Cenan - 1 year ago 72
Ruby Question

Check if two or more values exist in an array

I get this response in Ruby:

puts templateid --> ["10001", "10404"]

The first one should be #{mstmplid} and the second one should be #{ostmplid}. I want to check if this array contains these two values with the following function:

if templateid.all? { |x| ["#{mstmplid}", "#{ostmplid}"].include?(x) }
puts "OK"

Unfortunatelyy templateid.all? is the same with templateid.any? so it will check if any of the specified values are in the array. How can I check if both values are there?

Answer Source

If this two arrays always have just 2 elements, you can check it just by:

templateid.sort == [mstmplid, ostmplid].map(&:to_s).sort

if you just want to check if mstmplid, ostmplid included in templateid you should write like this:

[mstmplid, ostmplid].map(&:to_s).all? { |x| templateid.include? x }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download