1

Possible Duplicate:
How to break outer cycle in Ruby?

array_1 = %W(http://www.abc.com www.xyz.com www.pqr.com)
array_2 = %W(www.abc.com www.exmple.com)
array_1.each do |a1|
  array_2.each do |a2|
    next if(a1.include?(a2))
  end
puts a1
end

I want to skip those entries which are present in array_2. Is there anyway I can skip printing a1 if condition is satisfied? Ruby doesn't have label like java and I want to skip outer loop. :(

Any help would be great

Community
  • 1
  • 1
benchwarmer
  • 2,764
  • 23
  • 25
  • I don't think the question is duplicate; while the OP is indeed asking about how to break an outer cycle, refactoring seems the way to go. – tokland Dec 08 '11 at 11:38
  • @tokland code snippet works perfectly in my actual implementation. Thanks all for replying :) – benchwarmer Dec 08 '11 at 12:27

5 Answers5

4

You can write:

array_1.each do |a1|
  next if array_2.any? { |a2| a1.include?(a2) }
  ...
end
tokland
  • 66,169
  • 13
  • 144
  • 170
1

You can pass lambda with return statement to each method instead of block. Lambda function will return value, not the method enclosing lambda.

array_1 = %W(http://www.abc.com www.xyz.com www.pqr.com)
array_2 = %W(www.abc.com www.exmple.com)
array_1.each(&lambda do |a1|
  array_2.each do |a2|
    return if(a1.include?(a2))
  end
  puts a1
end)
Aliaksei Kliuchnikau
  • 13,589
  • 4
  • 59
  • 72
  • break will exit the current loop, but return will exit a function. so putting that in a function like Alex is a good way to do it. in other languages you'd be able to use the evil goto :) – Joseph Le Brech Dec 08 '11 at 11:17
1

Instead of trying to mimic other languages, you can do something like this instead:

array_1.product(array_2).each do |a1, a2|
  next if(a1.include?(a2))
end

or, more idiomatic:

array_1.product(array_2).reject{ |a1, a2|
  a1.include?(a2)
}.each{ |a1, a2|
  # do something here
}
Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
1

[Edit]Misread the input. This should be better. The any? method quits searching if one match is found.

array_1 = %W(http://www.abc.com www.xyz.com www.pqr.com)
array_2 = %W(www.abc.com www.exmple.com)

puts array_1.reject{|a1| array_2.any?{|a2| a1.include?(a2)} }

But if you insist in breaking out of a loop, there is catchand throw:

array_1.each do |a1|
  catch :its_in do
    array_2.each do |a2|
      throw :its_in if(a1.include?(a2))
    end
  puts a1
  end
end
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • 1
    substraction of arrays is a good idea, but look at the values, the OP really needs test inclusion, they are not equal. – tokland Dec 08 '11 at 15:10
0

You could use a while loop

This might work:

busy = true
while busy
  array1.each do |a1|
    array2.each do |a2|

       busy = false
    end
  end
end
Joseph Le Brech
  • 6,541
  • 11
  • 49
  • 84