我正在寻求最简洁的方法
给出以下数组:
['a','b','c']
如何得到这个:
{'a'=> 1,'b'=> 2, 'c'=> 3}
和
[['a',1],['b',2],['c',3]]
我心里想的很少,只想看看你的解决方案:)
答案 0 :(得分:4)
a.zip(1..a.length)
和
Hash[a.zip(1..a.length)]
答案 1 :(得分:2)
# 1.8.7+:
['a','b','c'].each_with_index.collect {|x,i| [x, i+1]} # => [["a", 1], ["b", 2], ["c", 3]]
# pre-1.8.7:
['a','b','c'].enum_with_index.collect {|x,i| [x, i+1]}
# 1.8.7+:
Hash[['a','b','c'].each_with_index.collect {|x,i| [x, i+1]}] # => {"a"=>1, "b"=>2, "c"=>3}
# pre-1.8.7:
Hash[*['a','b','c'].enum_with_index.collect {|x,i| [x, i+1]}.flatten]
答案 2 :(得分:1)
如果你想简洁快速,1.8.5兼容性,这是我发现的最好的:
i=0
h={}
a.each {|x| h[x]=i+=1}
在1.8.5中运行的Martin的版本是:
Hash[*a.zip((1..a.size).to_a).flatten]
但这比上述版本慢2.5倍。
答案 3 :(得分:0)
aa=['a','b','c']
=> ["a", "b", "c"] #Anyone explain Why it became double quote here??
aa.map {|x| [x,aa.index(x)]} #assume no duplicate element in array
=> [["a", 0], ["b", 1], ["c", 2]]
Hash[*aa.map {|x| [x,aa.index(x)]}.flatten]
=> {"a"=>0, "b"=>1, "c"=>2}