November 21, 2016
This blog is part of our Ruby 2.4 series.
Enumerable#chunk method can be used on enumerator object to group consecutive items based on the value returned from the block passed to it.
[1, 4, 7, 10, 2, 6, 15].chunk { |item| item > 5 }.each { |values| p values }
=> [false, [1, 4]]
[true, [7, 10]]
[false, [2]]
[true, [6, 15]]
Prior to Ruby 2.4, passing a block to chunk
method was must.
array = [1,2,3,4,5,6]
array.chunk
=> ArgumentError: no block given
In Ruby 2.4, we will be able to use chunk without passing block. It just returns the enumerator object which we can use to chain further operations.
array = [1,2,3,4,5,6]
array.chunk
=> <Enumerator: [1, 2, 3, 4, 5, 6]:chunk>
Let's take the case of listing consecutive integers in an array of ranges.
# Before Ruby 2.4
integers = [1,2,4,5,6,7,9,13]
integers.enum_for(:chunk).with_index { |x, idx| x - idx }.map do |diff, group|
[group.first, group.last]
end
=> [[1,2],[4,7],[9,9],[13,13]]
We had to use
enum_for here as
chunk
can't be called without block.
enum_for
creates a new enumerator object which will enumerate by calling the
method passed to it. In this case the method passed was chunk
.
With Ruby 2.4, we can use chunk
method directly without using enum_for
as it
does not require a block to be passed.
# Ruby 2.4
integers = [1,2,4,5,6,7,9,13]
integers.chunk.with_index { |x, idx| x - idx }.map do |diff, group|
[group.first, group.last]
end
=> [[1,2],[4,7],[9,9],[13,13]]
If this blog was helpful, check out our full blog archive.