Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an each_if in ruby?

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?

like image 581
Ólafur Waage Avatar asked Mar 06 '11 18:03

Ólafur Waage


People also ask

Is there a for loop in Ruby?

“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.

What is .each do in Ruby?

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.

How do you make a loop in Ruby?

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 ...

How do you go through an array in Ruby?

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.

How do you stop a loop in Ruby?

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.

What does each return in Ruby?

#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.


2 Answers

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}
like image 52
Marc-André Lafortune Avatar answered Nov 15 '22 10:11

Marc-André Lafortune


You could use take_while:

@list.take_while { |i| i <= 11 }.each { |i| puts i }
like image 27
mattexx Avatar answered Nov 15 '22 08:11

mattexx