获取数组哈希值

时间:2012-07-10 12:31:28

标签: ruby-on-rails ruby ruby-on-rails-3 loops

所以我试图从这一系列哈希中抓住所有高中和研究生院:

"education": [
    {
      "school": {
        "id": "110703012290674", 
        "name": "Kunskapsgymnasiet Malmö"
      }, 
      "year": {
        "id": "136328419721520", 
        "name": "2009"
      }, 
      "type": "High School"
    }, 
    {
      "school": {
        "id": "112812485399398", 
        "name": "Malmö University"
      }, 
      "year": {
        "id": "118118634930920", 
        "name": "2012"
      }, 
      "concentration": [
        {
          "id": "104076956295773", 
          "name": "Computer Science"
        }
      ], 
      "type": "Graduate School", 
      "classes": [
        {
          "id": "165093923542525", 
          "name": "Programmering", 
          "description": "Kursen fokuserar på metoder och tekniker vid utveckling av webbapplikationer med hjälp av HTML5."
        }
      ]
    }
  ],

像这样:

def add_friends
    facebook.get_connections("me", "friends",   :fields => "name, id, education").each do |hash|
      self.friends.where(:name => hash['name'], :uid => hash['id'], 
                                                :highschool_name => hash['education']['school']['name'] if hash['type'] == "High School",
                                                :graduateschool_name => hash['education']['school']['name'] if hash['type'] == "Graduate School").first_or_create
    end
  end

我尝试过这样的事情:

def add_friends
    friends_data = facebook.get_connections("me", "friends",   :fields => "name, id, education")
    friends_data.each do |hash|
      friend.name = hash["name"]
      friend.uid = hash["id"]

      if hash["education"]
        hash["education"].each do |e|
          if e["type"] == "High School"
            friend.highschool_name = e["school"]["name"] if (!hash["education"].blank? && !e["school"].blank?)

          elsif e["type"] == "Graduate School"
            friend.graduateschool_name = e["school"]["name"] if (!hash["education"].blank? && !e["school"].blank?)
          end
        end
      end
      friend.save!
      friend
  end
end

但是我得到了这个错误:undefined local variable or method朋友' 我认为缺少与朋友模型的连接缺失..

1 个答案:

答案 0 :(得分:0)

您可能需要查看Array#select您可以指定条件来获取符合certein标准的所有值:

schools.select{|school| school["type"] == "High School" || school["type"] == "Graduate School"}
相关问题