【发布时间】:2009-10-20 05:25:17
【问题描述】:
我正在寻找最简洁的方法
给定以下数组:
['a','b','c']
如何获得:
{'a'=> 1,'b'=> 2, 'c'=> 3}
和
[['a',1],['b',2],['c',3]]
我想到的解决方案很少,只是想看看你的:)
【问题讨论】:
我正在寻找最简洁的方法
给定以下数组:
['a','b','c']
如何获得:
{'a'=> 1,'b'=> 2, 'c'=> 3}
和
[['a',1],['b',2],['c',3]]
我想到的解决方案很少,只是想看看你的:)
【问题讨论】:
a.zip(1..a.length)
和
Hash[a.zip(1..a.length)]
【讨论】:
# 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]
【讨论】:
如果你想要简洁快速,以及 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 倍。
【讨论】:
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}
【讨论】: