迭代Hash时的TypeError

时间:2011-01-02 17:40:58

标签: ruby

我有以下哈希:

{
  "groups" => [
    {
      "type" => "Nearby", 
      "venues" => [
        {
          "id" => 4450132, 
          "name" => "Position2", 
          "address" => "Domlur", 
          "city" => "Bangalore", 
          "state" => "Karnataka/India", 
          "zip" => "560037", 
          "verified" => false, 
          "geolat" => 12.9566921, 
          "geolong" => 77.6407258, 
          "stats" => {
            "herenow" => "0"
          }, 
          "twitter" => "position2", 
          "hasTodo" => "false", 
          "distance" => 0
          },...

我想迭代它并找到所有'name'属性。我的代码如下:

response["groups"]["Nearby"]["venues"].each do |key|
  logger.debug key['name']
end

但我一直在收到错误:

TypeError (can't convert String into Integer):

我在红宝石1.9上。

3 个答案:

答案 0 :(得分:3)

response["groups"]是一个数组。数组由整数索引,而不是字符串。

如果您想获得类型为“附近”的群组,您可以使用:

response["groups"].find {|h| h["type"] == "Nearby}["venues"].each ...

答案 1 :(得分:1)

使用它:

response["groups"][0]["venues"].each do |key|
 logger.debug key['name']
end

原因是您的响应[“groups”]对象实际上是一个数组而不是一个地图。

答案 2 :(得分:1)

如果我清理哈希值,那么它就可以正常平衡:

data = {
  "groups" => [
    {
      "type" => "Nearby",
      "venues" => [
        {
          "id" => 4450132,
          "name" => "Position2",
          "address" => "Domlur",
          "city" => "Bangalore",
          "state" => "Karnataka/India",
          "zip" => "560037",
          "verified" => false,
          "geolat" => 12.9566921,
          "geolong" => 77.6407258,
          "stats" => {
            "herenow" => "0"
          },
          "twitter" => "position2",
          "hasTodo" => "false",
          "distance" => 0
        }
      ]
    }
  ]
}

我可以使用:

迭代哈希查找'name'
data['groups'].map{ |i| i['venues'].map{ |j| j['name'] } } # => [["Position2"]]

由于数据是嵌套的,因此将嵌套生成的提取数据。要展平它,请使用flatten

data['groups'].map{ |i| i['venues'].map{ |j| j['name'] } }.flatten # => ["Position2"]