call next on ruby loop from external method

前端 未结 3 1629
孤城傲影
孤城傲影 2021-01-11 14:16

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
         


        
3条回答
  •  感动是毒
    2021-01-11 14:39

    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
    

提交回复
热议问题