I'm seeking the most concise way to do this
Given the following Array:
['a','b','c']
how to get this:
{'a'=> 1,'b'=> 2, 'c'=> 3}
and
[['a',1],['b',2],['c',3]]
I have few sol开发者_运维问答utions at mind, just want to see yours :)
a.zip(1..a.length)
and
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]
If you want concise and fast, and 1.8.5 compatability, this is the best I've figured out:
i=0
h={}
a.each {|x| h[x]=i+=1}
The version of Martin's that works in 1.8.5 is:
Hash[*a.zip((1..a.size).to_a).flatten]
But this is 2.5x slower than the above version.
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}
精彩评论