2011-08-02 1 views
0

제가관계, 중첩 된 요소의 주파수를 얻기는

  • 점포의 배열시에 속하는

    • 현에 속하는

      • 개체 개체 개체가 유지
    나는 현, 다음 도시, 다음 주파수에 의해 나열 해시와 끝까지 싶습니다

    ...

나는이 함께했다,하지만 .. 정말

을 취소 rubylike을 느낀다
city_by_prefecture = shop_list.reduce({}){ |h,e| 
    if h[e.prefecture.name].nil? 
    h[e.prefecture.name] = {e.city.name => 1} 
    elsif h[e.prefecture.name][e.city.name].nil? 
    h[e.prefecture.name][e.city.name] = 1 
    else 
    h[e.prefecture.name][e.city.name] += 1 
    end 
    h 
} 

이렇게하는 것이 좋습니다.

+0

가능한 중복 [해시 \의 [ "는"\] 존재하지 않는 경우 "는"\] \ [ "B"\] = "C"를 해시 \의 [을 할당하는 방법?] (http://stackoverflow.com/questions/5878529/how-to-assign-hashab-c-if-hasha-doesnt-exist) –

+1

당신은'h.has_key? (e.prefecture.name)' 'h [e.prefecture.name] .nil? '보다는 오히려 당신이 요구하는 것이 더 분명하기 때문입니다. 또한,'reduce'보다는'each_with_object'를 사용하십시오, 그래서 당신은 블록의 끝에'h'를 넣을 필요가 없습니다. –

+0

앤드류 감사합니다. 나는'each_with_object'에 대해 몰랐다. – minikomi

답변

1
city_by_prefecture = shop_list.each_with_object({}){ |e,h| 
    h[e.prefecture.name] ||= Hash.new(0) 
    h[e.prefecture.name][e.city.name] += 1 
} 
+0

훨씬 더 깨끗합니다! 감사. – minikomi

0
shops = [ 
    OpenStruct.new(:prefacture => "pre1", :city => "city1"), 
    OpenStruct.new(:prefacture => "pre1", :city => "city1"), 
    OpenStruct.new(:prefacture => "pre1", :city => "city2"), 
    OpenStruct.new(:prefacture => "pre2", :city => "city3"), 
] 

counts = Hash[shops.group_by(&:prefacture).map do |prefacture, shops_in_prefacture| 
    [prefacture, Hash[shops_in_prefacture.group_by(&:city).map do |city, shops_in_city| 
    [city, shops_in_city.size] 
    end]] 
end] 
# {"pre1"=>{"city1"=>2, "city2"=>1}, "pre2"=>{"city3"=>1}}