在哈希中存储重复键

时间:2015-04-25 09:28:00

标签: ruby hash

我希望将重复的密钥与student_hash中的值一起存储,但由于ruby中缺少multimap,因此不允许使用。一种解决方案是基于selection(id/type/school_id)在单独的两个数组中捕获所有这些信息,但输入数据可能具有如此大的深度,并且无法确定数组大小。可以使用哈希实现相同的行为(预期输出)吗?请建议。

预期产出:

{:id=>"101", :type=>"junior", :school_id=>"IS1.4598"}
{:id=>"103", :type=>"Senior", :school_id=>"IS1.098"}

代码:

require 'json'

raw_data='{
  "Enquiry": "get_all_student_info",
  "success": true,
  "payload": [
    {
      "standard_version": "1.4",
      "country_id": "USA_01",
      "parent": "USA_IS1",
      "id": "101",
      "company": "Govt",
      "type": "Junior",
      "subsystem_type": "Govtgirlsschool",
      "school_id": "IS1.098"

    },
    {
      "standard_version": "1.4",
      "country_id": "NZ_01",
      "parent": "NZ_IS1",
      "id": "103",
      "company": "Private",
      "type": "Senior",
      "subsystem_type": "Govtboysschool",
      "school_id": "IS1.098"

    }
  ],
  "error": ""
}'

def student_hash(set, result = {})
  if set.class == Hash 
    set.each do |k, v|
      if("#{k}"=="id" || "#{k}"=="type"  || "#{k}"=="school_id")
        puts result ["#{k}".to_sym] = "#{v}"
      end
      if v.class == Hash
        result = student_hash(v, result)
      elsif v.class == Hash || v.class == Array
        result = student_hash(v, result) 
      end
    end
  elsif set.class == Array
    set.each do |a|
      result = student_hash(a, result)
    end
  end
  result
end

student_hash(JSON.parse(raw_data))
# => {:id=>"103", :type=>"Senior", :school_id=>"IS1.098"}

3 个答案:

答案 0 :(得分:2)

不太清楚但是,这足以满足raw_data

的预期输出
data = JSON.parse(raw_data)
data["payload"].map {|i| { :id => i["id"], type: i["type"], school_id: i["school_id"] }}

现在你可以打印锄头了。

答案 1 :(得分:1)

尝试使用以下功能,它会给出您期望的结果。

def content_display( result = [] )
student_array = []
@array = []
result["payload"].map {|i|
student_array={ :id => i["id"], :type => i["type"], :school_id =>  i["subsystem_instance_id"] }
@array << student_array
}
 @array
end
array=content_display(JSON.parse(raw_data))
puts array

答案 2 :(得分:0)

我认为这可能对你有所帮助。

all_data = []

row = {:id=>"101", :type=>"junior", :school_id=>"IS1.4598"} 

all_data << row

例如

students = Student.all

all_student = []

students.each do |student|
  student_hash = {:id=>student.id, :type=>student.type, :school_id=>student.school_id}
  all_student << student_hash
end

puts all_student

你会得到类似的结果

[{:id=>"101", :type=>"junior", :school_id=>"IS1.4598"}
{:id=>"103", :type=>"Senior", :school_id=>"IS1.098"}]