I가 배열 :루비 그룹화 요소
a = [1, 3, 1, 3, 2, 1, 2]
내가 값으로 그룹 원하지만 그것을 인덱스를 저장, 그래서 결과는이 같은 모습이어야합니다
[[0, 2, 5], [1, 3], [4, 6]]
또는 해시
{1=>[0, 2, 5], 3=>[1, 3], 2=>[4, 6]}
이제는 꽤 못생긴 큰 코드를 사용하고 있습니다.
struc = Struct.new(:index, :value)
array = array.map.with_index{ |v, i| struc.new(i, v) }.group_by {|s| s[1]}.map { |h| h[1].map { |e| e[0]}}
`
양호 또는 'a.each_with_index.with_object (Hash.new {| h, k | h [k] = []}) {((e, i), h | h [e] << i}'. –
감사합니다 @CarySwoveland : TIL'with_object'는 전에는 그 방법을 들여다 보지 않았습니다. – spickermann
[Enumerator # with_index] (http://ruby-doc.org/core-2.1.5/Enumerator.html#method-i-with_index)를 사용할 수도 있습니다 : a.each_with_object (Hash.new {| h, k | h [k] = []}). with_index {| (e, h), i | h [e] << i}'. 블록 변수의 다른 순서를 주목하십시오. 경사면. –