如何遍历可枚举的第一个元素

时间:2021-04-13 14:29:30

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?

我希望do的结果是2,3,因为我已经读过了a的第一个元素。我如何优雅地实现2,3的结果?

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.

为了澄清,我不想跳过第一个条目,我只是想以不同的方式处理它。所以我想要b和循环。

5 个解决方案

#1


28  

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

#2


4  

You could do

你可以做到

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

EDIT:

编辑:

Use the map method

使用map方法

b = [1,2,3].drop(1).map{|x| x}
=> b will be [2, 3]

#3


2  

Try this:

尝试这个:

a.shift    
a.each do |x| puts x end

#4


1  

As a sidenote, if you're trying to map over all but the first element of an array, array.drop(1).map {} obviously won't work. Instead, you can do something like:

作为旁注,如果你试图映射除数组的第一个元素之外的所有元素,array.drop(1).map {}显然不起作用。相反,你可以这样做:

[1,2,3].instance_eval { |a| [a.first] + a.drop(1).map { |e| e + 1 } }

#5


0  

Try the following code

请尝试以下代码

a=[1,2,3]
a.drop(1)

#1


28  

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

#2


4  

You could do

你可以做到

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

EDIT:

编辑:

Use the map method

使用map方法

b = [1,2,3].drop(1).map{|x| x}
=> b will be [2, 3]

#3


2  

Try this:

尝试这个:

a.shift    
a.each do |x| puts x end

#4


1  

As a sidenote, if you're trying to map over all but the first element of an array, array.drop(1).map {} obviously won't work. Instead, you can do something like:

作为旁注,如果你试图映射除数组的第一个元素之外的所有元素,array.drop(1).map {}显然不起作用。相反,你可以这样做:

[1,2,3].instance_eval { |a| [a.first] + a.drop(1).map { |e| e + 1 } }

#5


0  

Try the following code

请尝试以下代码

a=[1,2,3]
a.drop(1)