繁体   English   中英

Ruby:从数组/字符串Matchdata收集索引

[英]Ruby: Collect index from Array/String Matchdata

我是Ruby的新手,这是我的问题:我想遍历Array或String以获得与正则表达式匹配的字符的索引。

样本数组/字符串

 a = %q(A B A A C C B D A D)
 b = %w(A B A A C C B D A D)

我需要的是变量a或b之类的东西;

#index of A returns;
[0, 2, 3,8]

#index of B returns
[1,6]

#index of C returns
[5,6]
#etc

我试着与

z = %w()

a =~ /\w/.each_with_index do |x, y|

 puts z < y

end

但这锻炼得不好。 有什么解决办法吗?

对于数组,您可以使用

b.each_index.select { |i| b[i] == 'A' }

对于字符串,可以先将其拆分为一个数组( a.split(/\\s/) )。

如果要获取每个字符的索引作为哈希,这将起作用:

b = %w(A B A A C C B D A D)

h = {}
b.each_with_index { |e, i|
  h[e] ||= []
  h[e] << i
}
h
#=> {"A"=>[0, 2, 3, 8], "B"=>[1, 6], "C"=>[4, 5], "D"=>[7, 9]}

或作为“单线”:

b.each_with_object({}).with_index { |(e, h), i| (h[e] ||= []) << i }
#=> {"A"=>[0, 2, 3, 8], "B"=>[1, 6], "C"=>[4, 5], "D"=>[7, 9]}

如果要计算每个字母的出现次数,可以定义辅助方法:

def occurrences(collection)
  collection = collection.split(/\s/) if collection.is_a? String

  collection.uniq.inject({}) do |result, letter|
    result[letter] = collection.each_index.select { |index| collection[index] == letter }
    result
  end
end

# And use it like this. This will return you a hash something like this: 
# {"A"=>[0, 2, 3, 8], "B"=>[1, 6], "C"=>[4, 5], "D"=>[7, 9]}
occurrences(a)
occurrences(b)

这应该适用于String或Array。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM