Let's say I have this each loop in Ruby.
@list.each { |i|
puts i
if i > 10
break
end
}
Where I want to loop through the list until a condition is met.
This stung me as "un Ruby'ish" and since I'm new to Ruby, is there a Ruby way to do this?
“for” loop has similar functionality as while loop but with different syntax. for loop is preferred when the number of times loop statements are to be executed is known beforehand. It iterates over a specific range of numbers.
The each() is an inbuilt method in Ruby iterates over every element in the range. Syntax: range1.each(|el| block) Parameters: The function accepts a block which specifies the way in which the elements are iterated. Return Value: It returns every elements in the range.
The simplest way to create a loop in Ruby is using the loop method. loop takes a block, which is denoted by { ... } or do ... end . A loop will execute any code within the block (again, that's just between the {} or do ...
The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.
#Each and #Map They will both iterate (move through) an array, but the main difference is that #each will always return the original array, and #map will return a new array. create a new object with each: #each_with_object is a useful method that lets you add to a given object during each iteration.
You can use Enumerable#detect
or Enumerable#take_while
, depending on the result you want.
@list.detect { |i|
puts i
i > 10
} # Returns the first element greater than 10, or nil.
As others have noted, a better style would be to first make your sub-selection and then act on it, e.g.:
@list.take_while{ |i| i <= 10 }.each{|i| puts i}
You could use take_while:
@list.take_while { |i| i <= 11 }.each { |i| puts i }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With