Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call next on ruby loop from external method

Tags:

ruby

in Ruby it's easy to tell loop to go to next item

(1..10).each do |a|
  next if a.even?
  puts a
end

result =>

1
3   
5
7
9

but what if I need to call next from outside of the loop (e.g.: method)

def my_complex_method(item)
  next if item.even?  # this will obviously fail 
end

(1..10).each do |a|
  my_complex_method(a)
  puts a
end

only solution I found and works is to use throw & catch like in SO question How to break outer cycle in Ruby?

def my_complex_method(item)
  throw(:skip) if item.even? 
end

(1..10).each do |a|
  catch(:skip) do   
    my_complex_method(a)
    puts a
  end
end

My question is: anyone got any more niftier solution to do this ?? or is throw/catch only way to do this ??

Also what If I want to call my_complex_method not only as a part of that loop (=> don't throw :skip) , can I somehow tell my method it's called from a loop ?

like image 920
equivalent8 Avatar asked Jul 09 '13 10:07

equivalent8


2 Answers

You complex method could return a boolean, and then you compare on your loop like this:

def my_complex_method(item)
  true if item.even? 
end

(1..10).each do |a|
  next if my_complex_method(a)
  puts a
end

A simple approach, but different from the try catch one.

UPDATE

As item.even? already return a boolean value, you don't need the true if item.even? part, you can do as follow:

def my_complex_method(item)
  item.even? 
end
like image 70
MurifoX Avatar answered Sep 17 '22 13:09

MurifoX


Enumerator#next and Enumerator#peek will be good option to goo :

def my_complex_method(e)
  return if e.peek.even? 
  p e.peek
end
enum = (1..5).each
enum.size.times do |a|
  my_complex_method(enum)
  enum.next
end

Output

1
3
5
like image 39
Arup Rakshit Avatar answered Sep 19 '22 13:09

Arup Rakshit