2014-01-30 111 views
0

返回子元件的陣列我有以下結構:紅寶石使用地圖

"countries": [ 
    { 
    "states" :[ 
     { 
     "name" :"Texas", 
     "id": "a1" 
     }, 
     { 
     "name" :"Nebraska", 
     "id": "a1" 
     } 
    ] 
    }, 
    { 

    "states" :[ 
     { 
     "name" :"New York", 
     "id": "a1", 
     }, 
     { 
     "name" :"Florida", 
     "id": "a1" 
     } 
    ] 
    } 
] 

我想從上面返回所有狀態的數組。 這裏是我的嘗試:

countries.map { |country| country.states.map { |state| state.name } } 

但只返回第2 statest「得克薩斯」和內布拉斯加州。

有人能告訴我我在做什麼錯嗎?

+0

'countries.map {| country | country ['states']。map {| state | state.name}}' – apneadiving

+0

你的「結構」看起來很少有錯誤。你是如何生成它的? – vee

+0

你已經錯過了'{'在這之前'狀態':'}, 「states」:['' –

回答

0

您的結構是不正確的,所以修正:

countries = [ 
     { 
     "states" => [ 
      { 
      "name" => "Texas", 
      "id"=> "a1" 
      }, 
      { 
      "name"=> "Nebraska", 
      "id"=> "a1" 
      } 
     ] 
     }, 
     { 
     "states" => [ 
      { 
      "name"=> "New York", 
      "id"=> "a1", 
      }, 
      { 
      "name" =>"Florida", 
      "id"=> "a1" 
      } 
     ] 
     } 
    ] 

紅寶石是不接受「:」對於一些奇怪的原因字符串。這樣的(這是不工作):

countries = [ 
     { 
     "states": [ 
      { 
      "name": "Texas", 
      "id": "a1" 
      }, 
      { 
      "name": "Nebraska", 
      "id": "a1" 
      } 
     ] 
     }, 
     { 
     "states": [ 
      { 
      "name": "New York", 
      "id": "a1", 
      }, 
      { 
      "name" :"Florida", 
      "id": "a1" 
      } 
     ] 
     } 
    ] 

對於這一點,你可以這樣做:

countries.map{ |c| c["states"].map{|s| s["name"]}}.flatten 
#=> ["Texas", "Nebraska", "New York", "Florida"] 

或者如果你重複值,那麼:

countries.map{ |c| c["states"].map{|s| s["name"]}}.flatten.uniq 
#=> ["Texas", "Nebraska", "New York", "Florida"] 

我希望這幫助。

0

去Surya的答案,它是同樣的解決方案。只想顯示我如何寫它:

countries.map{|x|x['states']} 
     .flatten 
     .map{|x|x['name']}