Skim Array two by two

Hi,

Is it possible to get 2 elements at once ?

[1,2,3,4].each {|a,b| puts a;puts b;puts ‘x’}
produces
1,
nil
x
2
nil
x
3
nil
x
4
nil
x

I’d like to get

1
2
x
3
4
x

Thanks !

On Fri, 2 Feb 2007, Mickael Faivre-Macon wrote:

nil
1
2
x
3
4
x

Thanks !

harp:~ > cat a.rb
require ‘enumerator’

puts
%w( a b c d e ).each_cons(2){|x,y| p [x,y]}

puts
%w( a b c d e ).each_slice(2){|x,y| p [x,y]}
harp:~ > ruby a.rb

[“a”, “b”]
[“b”, “c”]
[“c”, “d”]
[“d”, “e”]

[“a”, “b”]
[“c”, “d”]
[“e”, nil]

-a

On Feb 1, 2007, at 12:26 PM, Mickael Faivre-Macon wrote:

Is it possible to get 2 elements at once ?

I’d like to get

1
2
x
3
4
x

require “enumerator”
=> true

[1, 2, 3, 4].each_slice(2) { |a, b| puts a, b, “x” }
1
2
x
3
4
x
=> nil

Hope that helps.

James Edward G. II

thanks everybody !

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs