Back to Blog

CSV::Row#each etc. return enumerator when no block given

This blog is part of our Ruby 2.4 series.

In Ruby 2.3, These methods do not return enumerator when no block is given.

Ruby 2.3

1
2CSV::Row.new(%w(banana mango), [1,2]).each #=> #<CSV::Row "banana":1 "mango":2>
3
4CSV::Row.new(%w(banana mango), [1,2]).delete_if #=> #<CSV::Row "banana":1 "mango":2>
5

Some methods raise exception because of this behavior.

1
2> ruby -rcsv -e 'CSV::Table.new([CSV::Row.new(%w{banana mango}, [1, 2])]).by_col.each'
3 #=> /Users/sushant/.rbenv/versions/2.3.0/lib/ruby/2.3.0/csv.rb:850:in `block in each': undefined method `[]' for nil:NilClass (NoMethodError)
4  from /Users/sushant/.rbenv/versions/2.3.0/lib/ruby/2.3.0/csv.rb:850:in `each'
5  from /Users/sushant/.rbenv/versions/2.3.0/lib/ruby/2.3.0/csv.rb:850:in `each'
6  from -e:1:in `<main>'
7

Ruby 2.4 fixed this issue.

Ruby 2.4

1
2CSV::Row.new(%w(banana mango), [1,2]).each #=> #<Enumerator: #<CSV::Row "banana":1 "mango":2>:each>
3
4CSV::Row.new(%w(banana mango), [1,2]).delete_if #=> #<Enumerator: #<CSV::Row "banana":1 "mango":2>:delete_if>
5

As we can see, these methods now return an enumerator when no block is given.

In Ruby 2.4 following code will not raise any exception.

1
2> ruby -rcsv -e 'CSV::Table.new([CSV::Row.new(%w{banana mango}, [1, 2])]).by_col.each'
3

You might also like

If you liked this blog post, check out similar ones from BigBinary