2013-10-12 5 views
13

배열에 X 개의 값이 있습니다. 다음 배열은 4 개만 있습니다. 그러나 코드가 동적이어야하며 4 개의 배열 객체 만 갖는 것에 의존하지 않아야합니다.Ruby에서 배열 인덱스 값을 유지하면서 배열을 해시로 변환

hash = {0 => 'Adult', 1 => 'Family', 2 => 'Single', 3 => 'Child'}

배열 개체가 같은 해시는 많은 키/값 쌍을 가져야한다

하고, 값 :

array = ["Adult", "Family", "Single", "Child"]

나는 다음과 같다 해시에 array을 변환 할 각 객체에 대해 0부터 시작하여 1 씩 증가해야합니다. Enumerable#each_with_index를 사용

답변

15

은 :

Hash[array.each_with_index.map { |value, index| [index, value] }] 
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 

@hirolau은 주석으로, each_with_index.mapmap.with_index과 같이 쓸 수있다. Hash#invert를 사용

Hash[array.map.with_index { |value, index| [index, value] }] 
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 

UPDATE

Alterantive :

Hash[array.map.with_index{|*x|x}].invert 
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 
Hash[[*array.map.with_index]].invert 
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 
+0

굉장 시도를 않습니다. 팁 고마워. – Luigi

+3

each_with_index.map은 map.with_index로 작성할 수도 있습니다. – hirolau

+2

해시 [배열 .map.with_index {| * x | x}]. 반전 – hirolau

1
Hash[*(0..array.size-1).to_a.zip(array)] 
    => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 
+4

니스! 우리는 그것을 더 짧게 만들 수 있습니다 -'Hash [(0 ... array.size) .zip (array)] ' –

+0

아주 좋은, @Alex. 팁 고마워. 나는 범위에서 3 개의 점들 (골프를 제외하고)을 피하는 경향이 있습니다 - 너무 쉽게 놓치기 쉽습니다. –

4

또 다른 하나

Hash[array.each_index.zip(array)] 
#=> {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 

최근 루비 버전 허용합니다 :

array.each_with_index.to_h.invert 
#=> {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 
0

array.each_with_index.inject({}){ |hash, (val, i)| hash[i]=val; hash } 
=> {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 
관련 문제