Ruby - 3 mins read

Ruby each_cons method

Devraj Boddu

Technical Consultant

each_cons image

In Ruby, there is a method called each_cons that is available for enumerable objects, such as arrays and ranges. This method allows you to iterate over elements in a collection in consecutive groups of a specified size, moving one element at a time. It is particularly useful when you want to work with sliding windows of elements within a collection.

The syntax each_cons is as follows:

enumerable.each_cons(n) do |group|
  # Code to be executed for each consecutive group of size 'n'
end

Here’s a breakdown of the parameters:

enumerable: This is an enumerable object like an array or a range that you want to iterate over. n: This is an integer that specifies the size of each consecutive group. Here’s an example of how you might use each_cons:

array = [1, 2, 3, 4, 5, 6, 7]
array.each_cons(3) do |group|
  puts group.inspect
end

In this example, each_cons(3) will iterate over the array in groups of three elements at a time, starting with [1, 2, 3], then [2, 3, 4], and so on until it reaches the end of the array.

Find sequences using the each_cons method in ruby

# Sample array of objects
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Define the sequence you want to find
sequence_to_find = [3, 4, 5]

# Method 1: Using each_cons
found = false
array.each_cons(sequence_to_find.length) do |sub_array|
  if sub_array == sequence_to_find
    found = true
    break
  end
end

if found
  puts "Sequence found in the array"
else
  puts "Sequence not found in the array"
end

each_cons method is used to iterate through an enumerable (such as an array or a range) in consecutive groups of a specified size. It’s a helpful method for finding sequences or patterns within the elements of the enumerable.

Written by Devraj Boddu

Other blogs

You may also like


Your one-stop shop for expert RoR services

join 250+ companies achieving top-notch RoR development without increasing your workforce.