views:

108

answers:

2

I am trying to use the Enumerable#each_slice. It doesn't work on my computer, stating that method is not found.

I am running ruby 1.8.6 (2008-08-11 patchlevel 287) [universal-darwin9.0]

API: http://ruby-doc.org/core/classes/Enumerable.html#M003142

Example:

(1..10).each_slice(3) {|a| p a} # I get NoMethodError: undefined method `each_slice' for 1..10:Range

What am I doing wrong?

+1  A: 

just compared 1.8.6 to 1.9 and it looks like

(1..10).respond_to? :each_slice

is true in 1.9 and false in 1.8.6. So, the doc you are using is not for 1.8.6. if you can upgrade to a newer version of Ruby easily it should give you that method on the Range.

Pete
Thanks, next time I'll check the docs version.
Pran
Not true actually. The linked docs are for 1.8.6. The docs for 1.8.7 and 1.9 have core-1.8.7 and core-1.9 respectively instead of core in their url. It's just that the core docs also list methods that are added to core classes by files in stdlib (yes, that sucks).
sepp2k
+5  A: 

In ruby 1.8.6 you have to require 'enumerator' (which is part of stdlib and has been merged into core in 1.8.7+) before using each_slice.

Sadly the ruby-doc lists methods that are added to core classes by stdlib without mentioning where the methods are from.

sepp2k
Thanks!FYI, I tried <require 'enumerable'> and it gave me an exception. On the other hand, <require 'enumerator'> worked and the method was available.
Pran
You're right, it's enumerator. My mistake.
sepp2k