Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

ruby - Convert an array to hash, where keys are the indices

I am transforming an array into a hash, where the keys are the indices and values are the elements at that index.

Here is how I have done it

# initial stuff
arr = ["one", "two", "three", "four", "five"]
x = {}

# iterate and build hash as needed
arr.each_with_index {|v, i| x[i] = v}

# result
>>> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Is there a better (in any sense of the word "better") way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
arr = ["one", "two", "three", "four", "five"]

x = Hash[(0...arr.size).zip arr]
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...