在ruby中查找多维数组中每个元素的索引

时间:2010-04-07 15:35:39

标签: ruby arrays multidimensional-array indexing

例如

:a=[["hello", "world"], ["good", "lord"], ["hello", "lord"]]

我需要找到并记录每个单词相对于超级数组的索引。 即

hello => 0,2
world => 0
lord => 1,2.

这是我的镜头,但它非常业余和冗长。

all_tokens=tokens.flatten
all_tokens.each do|keyword|                                                                                      
    tokens.each do|token_array|
        if token_array.include?keyword
            x << i
        end
        i=i+1
    end    
    y[k] = x.clone
    y=y.clear
end 

6 个答案:

答案 0 :(得分:4)

对vava的解决方案略有改进(imho):

tokens = [["hello", "world"], ["good", "lord"], ["hello", "lord"]]

tokens_hash = Hash.new{|h, k| h[k] = []}

tokens.each_with_index do |subarr, i|
  subarr.each do |word|
    tokens_hash[word] << i
  end
end

答案 1 :(得分:2)

ret = []
a.each_with_index {|x, i| if x.include?(keyword) then ret << i end }

答案 2 :(得分:2)

a.each_with_index.inject({}){|acc,(elem,i)|
  elem.each{|e|
    acc[e] ||= []
    acc[e] << i
  }
  acc
}
#=> {"hello"=>[0, 2], "world"=>[0], "good"=>[1], "lord"=>[1, 2]}

答案 3 :(得分:1)

tokens = [["hello", "world"], ["good", "lord"], ["hello", "lord"]]

tokens_hash = Hash.new([])

tokens.each_with_index do |subarr, i|
    subarr.each do |word|
        tokens_hash[word] = tokens_hash[word] + [i]
    end
end

p tokens_hash #=>{"good"=>[1], "world"=>[0], "lord"=>[1, 2], "hello"=>[0, 2]}

我的解决方案只扫描整个结构一次。

答案 4 :(得分:1)

只是为了咧嘴笑,一个功能性解决方案:

#!/usr/bin/ruby1.8

a = [["hello", "world"], ["good", "lord"], ["hello", "lord"]]

b = a.flatten.uniq.inject({}) do |hash, word|
  hash.merge(word => a.each_with_index.collect do |list, i|
               list.index(word) && i
             end.compact)
end

p b    # => {"world"=>[0], "good"=>[1], "lord"=>[1, 2], "hello"=>[0, 2]}

答案 5 :(得分:1)

a=[["hello", "world"], ["good", "lord"], ["hello", "lord"]]
result = Hash.new{|k,v| k[v] = []}
a.each_with_index{|b,i| b.each{|c| result[c] << i} }
result
#=> {"good"=>[1], "world"=>[0], "lord"=>[1, 2], "hello"=>[0, 2]}