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.
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.
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.
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.
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With