call next on ruby loop from external method

前端 未结 3 1610
孤城傲影
孤城傲影 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:30

    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
    
    0 讨论(0)
  • 2021-01-11 14:35

    If all you need is to take actions on only some of values, based on value returned by my_complex_method you could use enumerators wisely:

    (1..10).map { |a| [a, my_complex_method(a)] }.each do |a, success|
      puts a if success
    end
    
    You could define method accepting block and take some action in this block based on success or failure there: (1..10).each do |a| my_complex_method { |success| next if success } end Thanks to scoping, you are able not to use `catch`/`throw`, and call `next` based on processing status.
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题