Is everyone in ruby?

Say I have every loop in Ruby.

@list.each { |i| puts i if i > 10 break end } 

Where I want to iterate over the list until the condition is met.

This stung me as "un Ruby'ish", and since I'm new to Ruby, is there any way Ruby can do this?

+4
source share
2 answers

You can use Enumerable#detect or Enumerable#take_while , depending on the desired result.

 @list.detect { |i| puts i i > 10 } # Returns the first element greater than 10, or nil. 

As others noted, the best style would be to first make your sub-choice and then act on it, for example:

 @list.take_while{ |i| i <= 10 }.each{|i| puts i} 
+6
source

You can use take_while:

 @list.take_while { |i| i <= 11 }.each { |i| puts i } 
+3
source

Source: https://habr.com/ru/post/1342530/


All Articles