Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #2203
| From | Jesús Gabriel y Galán <jgabrielygalan@gmail.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: Splitting each_cons? |
| Date | 2011-04-03 13:51 -0500 |
| Organization | Service de news de lacave.net |
| Message-ID | <BANLkTinxmviTNe3XSgK-Qeqa8ESR58mjvQ@mail.gmail.com> (permalink) |
| References | <5871e9ab38bdcb62e11f435fc17d510d@ruby-forum.com> |
On Sun, Apr 3, 2011 at 8:45 PM, Simon Harrison <simon@simonharrison.net> 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.
Back to comp.lang.ruby | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Splitting each_cons? Simon Harrison <simon@simonharrison.net> - 2011-04-03 13:45 -0500
Re: Splitting each_cons? Jesús Gabriel y Galán <jgabrielygalan@gmail.com> - 2011-04-03 13:51 -0500
Re: Splitting each_cons? Simon Harrison <simon@simonharrison.net> - 2011-04-03 14:13 -0500
Re: Splitting each_cons? 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-03 15:24 -0500
Re: Splitting each_cons? Brian Candler <b.candler@pobox.com> - 2011-04-03 15:28 -0500
Re: Splitting each_cons? 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-03 15:35 -0500
Re: Splitting each_cons? Simon Harrison <simon@simonharrison.net> - 2011-04-03 16:07 -0500
Re: Splitting each_cons? Josh Cheek <josh.cheek@gmail.com> - 2011-04-03 17:36 -0500
Re: Splitting each_cons? Rob Biedenharn <Rob@AgileConsultingLLC.com> - 2011-04-04 07:42 -0500
Re: Splitting each_cons? 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-03 16:28 -0500
Re: Splitting each_cons? Simon Harrison <simon@simonharrison.net> - 2011-04-03 16:33 -0500
Re: Splitting each_cons? 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-03 16:35 -0500
Re: Splitting each_cons? Simon Harrison <simon@simonharrison.net> - 2011-04-03 16:51 -0500
csiph-web