How can I return something early from a block?

前端 未结 3 1375
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 23:41

If I wanted to do something like this:

collection.each do |i|
   return nil if i == 3

   ..many lines of code here..
end

How would I get t

相关标签:
3条回答
  • 2020-12-12 23:49

    In this instance, you can use break to terminate the loop early:

    collection.each do |i|
      break if i == 3
      ...many lines
    end
    

    ...of course, this is assuming that you're not actually looking to return a value, just break out of the block.

    0 讨论(0)
  • 2020-12-12 23:57

    next inside a block returns from the block. break inside a block returns from the function that yielded to the block. For each this means that break exits the loop and next jumps to the next iteration of the loop (thus the names). You can return values with next value and break value.

    0 讨论(0)
  • 2020-12-13 00:03
    #!/usr/bin/ruby
    
    collection = [1, 2, 3, 4, 5 ]
    
    stopped_at = collection.each do |i|
       break i if i == 3
    
       puts "Processed #{i}"
    end
    
    puts "Stopped at and did not process #{stopped_at}"
    
    0 讨论(0)
提交回复
热议问题