How do I create an exclusion for a array map in Ruby.
Here’s what I want to achieve,
a = [1,2,3,4]
b = [5,6,7,8]
a.map.each do |x|
b.map.each do |y|
if !(x == 1 && y == 7)
puts "#{x} and #{y}"
elsif !(x == 4 && y == 8)
puts "#{x} and #{y}"
end
end
end
1 and 5
1 and 6
1 and 7 # still here
1 and 8
2 and 5
2 and 6
2 and 7
2 and 8
3 and 5
3 and 6
3 and 7
3 and 8
4 and 5
4 and 6
4 and 7
4 and 8 # still here
However, it doesn’t work, how do I add an exception to these values being processed by map? Also if it’s possible to use inject/reject/filter function with the same goal.
To explain why 1 and 7 is still printing, step through the logic:
if !(x == 1 && y == 7)x == 1is true andy == 7is true, therefore!(true && true)is false, this is skipped.elsif !(x == 4 && y == 8)ifwas skipped, so theelsifis evaluated.x == 4is false (since x is still 1) andy == 8is false (since y is still 7). Therefore,!(false && false)is true, and theputsis reached.Because
xcan never be both 1 and 4 at the same time andycan never be 7 and 8 at the same time, either your if statement or your elsif statement will always succeed, and since both branches print, the values will be always printed, no matter what x and y are.As other answers said, you need to combine your clauses.