2014-01-30 110 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']}