Ruby - 3 mins read
Ruby each_cons method
![](/static/920246a99e77ca69c92057f708e6d226/21b76/boddhu_a499f3908d.jpg)
Devraj Boddu
Technical Consultant
![](/static/52e84073587bc15089104ebd5b171a1b/93450/ruby_90d3da9d64.webp)
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.