0
a=[11,22,31,224,44].to_enum
=> #<Enumerator: [11, 22, 31, 224, 44]:each>
a.select.with_index{|x| puts x if x<2 }
=> []
a.with_index(2)
=> #<Enumerator: #<Enumerator: [11, 22, 31, 224, 44]:each>:with_index(2)>
irb(main):011:0> a.with_index(2){|x| puts x if x==224}
224
=> [11, 22, 31, 224, 44]
a.with_index(2){|x| puts x if x < 224}
11
22
31
44
=> [11, 22, 31, 224, 44]

困惑: 这里我将起始偏移量设置为2。但是如果我们查看输出 - 怎么11 而不是31。正如在31位置上2th

a.with_index(2){|x| puts x if x > 224}
=> [11, 22, 31, 224, 44]
a.with_index(1){|x| puts x if x > 224}
=> [11, 22, 31, 224, 44]
a.with_index(1){|x| puts x if x < 224}
11
22
31
44
=> [11, 22, 31, 224, 44]
a.with_index(1){|x| puts x if x < 224}
11
22
31
44
=> [11, 22, 31, 224, 44]

困惑: 在这里,我将起始偏移量设置为1。但是如果我们查看输出 - 怎么11来而不是22。正如在22位置上1st

在考虑所有事实时,即使我们提到了起始偏移量,我也想知道 - 为什么enum#with_index不从提到的偏移量开始评估?

注意:是否有任何直接的方法来打印index内容?

4

1 回答 1

4

Enumerator#with_index has confusing documentation,but hopefully this will make it more clear.

a=[11,22,31,224,44].to_enum
=> [11, 22, 31, 224, 44]
a.with_index { |val,index| puts "index: #{index} for #{val}" }
index: 0 for 11
index: 1 for 22
index: 2 for 31
index: 3 for 224
index: 4 for 44

a.with_index(2) { |val,index| puts "index: #{index} for #{val}" }
index: 2 for 11
index: 3 for 22
index: 4 for 31
index: 5 for 224
index: 6 for 44

As you can see, what it actually does is offset the index, not start iterating from the given index.

于 2013-02-02T21:34:34.260 回答