On Sun, Apr 3, 2011 at 8:45 PM, Simon H. [email protected]
wrote:
I’m not sure if each_cons can do what I’m trying to achieve:
one : vol1
one : vol2
three : vol3
To achieve this, you don’t need each_cons, a simple each should suffice:
ruby-1.8.7-p334 :001 > films = [[“one”, “vol1”], [“one”, “vol2”],
[“three”, “vol3”]]
=> [[“one”, “vol1”], [“one”, “vol2”], [“three”, “vol3”]]
ruby-1.8.7-p334 :002 > films.each {|film| puts “#{film.first} :
#{film.last}”}
one : vol1
one : vol2
three : vol3
each_cons is typically used to traverse an array sliding several
elements at a time, for example:
ruby-1.8.7-p334 :003 > a = (1…20).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20]
ruby-1.8.7-p334 :004 > a.each_cons(3) {|x,y,z| p [x,y,z]}
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
[9, 10, 11]
[10, 11, 12]
[11, 12, 13]
[12, 13, 14]
[13, 14, 15]
[14, 15, 16]
[15, 16, 17]
[16, 17, 18]
[17, 18, 19]
[18, 19, 20]
Jesus.