Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over all but first element of an enumerable

Tags:

I run the following code:

> a = [1,2,3].collect  => #<Enumerator: [1, 2, 3]:collect>  > b = a.next  => 1  > a.each do |x| puts x end 1 2 3 => [nil, nil, nil]  

I would expect the result of the do to be 2, 3 since I've already read the first element of a. How I achieve a result of 2, 3 elegantly?

Edit:

To clarify, I don't want to skip the first entry, I just want to process it differently. So I want both b and the loop.

like image 582
Stefan Avatar asked Jun 05 '13 10:06

Stefan


People also ask

How do I get the first item of IEnumerable?

We can get first item values from IEnumerable list by using First() property or loop through the list to get respective element. IEnumerable list is a base for all collections and its having ability to loop through the collection by using current property, MoveNext and Reset methods in c#, vb.net.

How do you skip the first element of an array in Ruby?

Removing the first element If you don't want to modify the original array, you can use the drop() method in Ruby. In the above example, we have passed 1 as an argument to the drop() method. so it creates a new array by removing the first element from the prices array.

How to iterate through collection in C#?

An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time. When a yield return statement is reached, the current location in code is remembered.


2 Answers

How about this?

[1,2,3].drop(1).each {|x| puts x } # >> 2 # >> 3 

Here's how you can continue walking the iterator

a = [1,2,3]  b = a.each # => #<Enumerator: [1, 2, 3]:each> b.next # skip first one  loop do   c = b.next   puts c end # >> 2 # >> 3 
like image 160
Sergio Tulentsev Avatar answered Oct 26 '22 19:10

Sergio Tulentsev


You could do

a.drop(1).each do |x| puts x end 

EDIT:

Use the map method

b = [1,2,3].drop(1).map{|x| x} => b will be [2, 3] 
like image 25
Anand Shah Avatar answered Oct 26 '22 19:10

Anand Shah