@Arup 已经回答了您的问题,我想我可能会详细说明一下。 Arup 建议您这样做:
A.each_index.select{|i| V.include? A[i]}
在哪里
A = ["a","s","p","e","n"]
V = ["a","e","i","o","u"]
首先,A.each_index 是什么?在 IRB 中试一试:
e = A.each_index # => #<Enumerator: ["a", "s", "p", "e", "n"]:each_index>
e.class # => Enumerator
e.to_a # => [0, 1, 2, 3, 4]
所以枚举器e 是方法Enumerable#select 的接收者,Enumerable 是一个混合模块,包含在几个Ruby 类中,包括Enumerator。要检查吗?
e.respond_to?(:select) # => true
e.respond_to?(:map) # => true
e.respond_to?(:reduce) # => true
接下来,请注意A.each_index 不依赖于A 的内容,只依赖于它的大小,因此我们可以将其替换为从0 迭代到A.size - 1 的任何枚举器,例如:
m = A.size
m.times.select{|i| V.include? A[i]} # => [0, 3]
0.upto(m-1).select{|i| V.include? A[i]} # => [0, 3]
我们可以确认这些是 Enumerator 对象:
m.times.class # => Enumerator
0.upto(m-1).class # => Enumerator
include Enumerable 的其他主要类是 Array、Hash、Set、Range 和 IO(但是,从 Ruby 1.9 开始,不是 String),所以我们也可以这样做:
Array(0...m).select{|i| V.include? A[i]} # => [0, 3]
(0...m).select{|i| V.include? A[i]} # => [0, 3]
require 'set'
Set.new(0..m-1).select{|i| V.include? A[i]} # => [0, 3]
请注意,无论接收者的类别如何,select 都会返回一个数组。大多数(但不是全部)返回集合的可枚举方法返回一个数组,而不管接收者的类是什么。