2014-05-18 9 views
0

숫자 배열을 문자열 형식으로 가지고 있으며 키가 숫자이고 값이 해당 위치 인 해시 값으로 변환하려고합니다. 배열의 숫자. 그래서 예를 들면 :배열을 {value => position_in_array} 형식의 해시로 변환

["1", "5", "3"] 

가 발생한다 :

{ 1 => 0, 5 => 1, 3 => 2 } 

I가 작동하는 다음 코드 :

my_hash = {} 
my_array.each do |number_string| 
    my_hash[number_string.to_i] = my_array.index(number_string) 
end 

되는 반복 배열을 각각의 값 및 그 위치를 푸시 해시로.

더 짧고 우아한 방법이 있습니까? 아마도 Ruby의 to_a 함수와 비슷한 것일 수도 있지만, 더 많은 것은 to_h(options)입니다.

답변

4
Hash[["1", "5", "3"] 
.map.with_index{|e, i| [e.to_i, i]}] 
# => {1=>0, 5=>1, 3=>2} 

또는

["1", "5", "3"] 
.each_with_object({}).with_index{|(e, h), i| h[e.to_i] = i} 
# => {1=>0, 5=>1, 3=>2} 
1
arr = ["1", "5", "3"] 
ha = Hash[arr.map.with_index {|a, i| [a.to_i, i]}] 
puts "ha: #{ha.inspect}" 

irb(main):038:0> arr=["1", "5", "3"] 
=> ["1", "5", "3"] 
irb(main):039:0> Hash[arr.map.with_index {|a, i| [a, i]}] 
=> {"1"=>0, "5"=>1, "3"=>2} 
irb(main):040:0> Hash[arr.map.with_index {|a, i| [a.to_i, i]}] 
=> {1=>0, 5=>1, 3=>2} 
관련 문제