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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…