akshitBhatia
akshitBhatia

Reputation: 1151

Move to next iteration of a loop through a function inside the loop in ruby

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?

Upvotes: 2

Views: 320

Answers (1)

Wayne Conrad
Wayne Conrad

Reputation: 107999

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

Upvotes: 2

Related Questions