简体   繁体   中英

Array to Hash or 2 binary element Array

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 solutions at mind, just want to see yours :)

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]

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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