---
title: "Enumerable#chunk not mandatory in Ruby 2.4"
description:
  "Enumerable#chunk does not require a block to be passed along with it in Ruby
  2.4"
canonical_url: "https://www.bigbinary.com/blog/passing-block-with-enumerable-chunk-is-not-mandatory-in-ruby-2-4"
markdown_url: "https://www.bigbinary.com/blog/passing-block-with-enumerable-chunk-is-not-mandatory-in-ruby-2-4.md"
---

# Enumerable#chunk not mandatory in Ruby 2.4

Enumerable#chunk does not require a block to be passed along with it in Ruby 2.4

- Author: Abhishek Jain
- Published: November 21, 2016
- Categories: Ruby 2.4, Ruby

[Enumerable#chunk](https://ruby-doc.org/core-2.3.2/Enumerable.html#method-i-chunk)
method can be used on enumerator object to group consecutive items based on the
value returned from the block passed to it.

```ruby

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

```ruby

array = [1,2,3,4,5,6]
array.chunk

=> ArgumentError: no block given

```

### Enumerable#chunk without block in Ruby 2.4

In Ruby 2.4, we will be able to use
[chunk without passing block](https://bugs.ruby-lang.org/issues/2172). It just
returns the enumerator object which we can use to chain further operations.

```ruby

array = [1,2,3,4,5,6]
array.chunk

=> <Enumerator: [1, 2, 3, 4, 5, 6]:chunk>

```

### Reasons for this change

Let's take the
[case of listing](http://stackoverflow.com/questions/8621733/how-do-i-summarize-array-of-integers-as-an-array-of-ranges)
consecutive integers in an array of ranges.

```ruby

# 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](http://ruby-doc.org/core-2.3.2/Object.html#method-i-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

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

```

## Links

- [Human page](https://www.bigbinary.com/blog/passing-block-with-enumerable-chunk-is-not-mandatory-in-ruby-2-4)
