Ruby array access 2 consecutive(chained) elements at a time
Ruby reads your mind. You want cons ecutive elements?
[1, 2, 3, 4, 5, 6, 7, 8, 9].each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]
Iterate over loop accessing two elements if they exist
You can use each_cons
:
array.each_cons(2) do |a, b|
process(a, b)
end
How to iterate over an array in overlapping groups of n elements?
You can add nil
as the first element of your arr
and use Enumerable#each_cons
method:
arr.unshift(nil).each_cons(2).map { |first, second| [first, second] }
# => [[nil, "one"], ["one", "two"], ["two", "three"]]
(I'm using map
here to show what exactly is returned on each iteration)
Iterate pairwise through a ruby array
You are looking for each_cons
:
(1..6).each_cons(2) { |a, b| p a: a, b: b }
# {:a=>1, :b=>2}
# {:a=>2, :b=>3}
# {:a=>3, :b=>4}
# {:a=>4, :b=>5}
# {:a=>5, :b=>6}
How can I slice array values?
a.each_cons(2).to_a
#=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10]]
Iterate over a array and returning the next and the element before current
Take look at Enumerable#each_cons
method:
[nil, *array, nil].each_cons(3){|prev, curr, nxt|
puts "prev: #{prev} curr: #{curr} next: #{nxt}"
}
prev: curr: a next: b
prev: a curr: b next: c
prev: b curr: c next:
If you like, you can wrap it in new Array method:
class Array
def each_with_prev_next &block
[nil, *self, nil].each_cons(3, &block)
end
end
#=> nil
array.each_with_prev_next do |prev, curr, nxt|
puts "prev: #{prev} curr: #{curr} next: #{nxt}"
end
Overlapping equivalent of Array#slice
each_cons
(docs) does this. You just pass it the size of the chunks you want and it will yield them to the block you pass.
If you actually want the arrays, then you can of course chain this with to_a
, for example
(1..5).each_cons(3).to_a
Ruby Iteration - Trying to match two numbers in a single pass
Don't use
a.each_slice
To get a series of paired objects.
Use each_cons as suggested by steenslag or glenn mcdonald.
Enumerating over an array but passing a subset of the array to the block instead of a single element
each_cons(3)
behaves like that. It is in Enumerable (Array includes Enumerable), that's why you couldn't find it.
Related Topics
Printing the Source Code of a Ruby Block
Office 365 Rest API - Daemon Week Authentication
Why Is It Bad Style to 'Rescue Exception =≫ E' in Ruby
Why Do Ruby Setters Need "Self." Qualification Within the Class
Error When Running Rails App - Execjs::Runtimeerror
Ruby 1.9 Array.To_S Behaves Differently
Is There Any Difference Between the ':Key =≫ "Value"' and 'Key: "Value"' Hash Notations
How to Dynamically Create a Local Variable
How to Find Out the Current Route in Rails
Rails: How to Change the Title of a Page
Why Are Exclamation Marks Used in Ruby Methods