2

I am new to ruby, and I have been reading a lot of tutorials. Yesterday I SWEAR I read an example of the each statement (or something like it) that enumerated over an array, and then passed a subset of the array to the block. Here's an example, but the syntax is wrong (or I am using the wrong method) so this will not actually run.

arry = ["a", "b", "c", "d", "e"]

arry.each(3) {|a, b, c| puts a+b+c}

If I was using the right command, this would print:abc bcd cde; it takes the first three members of the array starting at the index and the enumeration ends when there isn't a string long enough to provide all three arguments. I can't remember how to do it and I can't seem to google the right thing to find it. Do any of you guys know?

Noah
  • 495
  • 2
  • 7
  • 21

3 Answers3

8

each_cons(3) behaves like that. It is in Enumerable (Array includes Enumerable), that's why you couldn't find it.

steenslag
  • 79,051
  • 16
  • 138
  • 171
  • Arg!!! I read the whole Array section on ruby-doc, and then I saw that it was a child of Object so I check Object just to be sure. I totally missed that it included the Enumerables module. Thanks! – Noah Jul 05 '12 at 15:02
2

you mean something like combination ?

arry.combination(3).each {|a, b, c| p a+b+c}
phoet
  • 18,688
  • 4
  • 46
  • 74
  • This was not quite what I was looking for, but very close. Coincedentally, a problem I was working on later needed `combination` so thank you for that. :) – Noah Jul 06 '12 at 17:44
1

How about each_slice?

arry.each_slice(3) {|a,b,c| p a+b+c}
Linuxios
  • 34,849
  • 13
  • 91
  • 116