2

I am trying to write a piece of code where i can move to the next iteration of a loop while inside a method called in the loop.

In sample code, this is what i am trying to do

def my a
    if a > 3
        next
    end
end

x = [1,2,3,4,5,6,7]

for i in x
    my i
    print i
end

This gives a syntax error.

One way to achieve this is by raising an error and catching it.

def my a
    if a > 3
        raise "Test"
    end
end

x = [1,2,3,4,5,6,7]

for i in x
    begin
        my i
        print i
    rescue Exception => e
        #do nothing
    end
end

But exceptions are expensive. I dont want to return anything from the function or set flag variables in the function because i want to keep the code clean of these flags.

Any ideas?

Jonas
  • 121,568
  • 97
  • 310
  • 388
akshitBhatia
  • 1,131
  • 5
  • 12
  • 20
  • 1
    By the way: `x.each do |i|` is more idiomatic Ruby than `for i in x`. See: http://stackoverflow.com/questions/3294509/for-vs-each-in-ruby – Wayne Conrad Nov 23 '15 at 11:08

1 Answers1

2

A Ruby way of having a function affect the caller's flow of control is for the caller to pass the function a block, which the function can then execute (or not):

def my a
  yield unless a > 3
end

x = [1,2,3,4,5,6,7]

for i in x
  my i do  
    print i
  end
end

# => 123

See also: Blocks and yields in Ruby

Community
  • 1
  • 1
Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191