Ruby嵌套哈希查找重复项

时间:2018-02-02 10:15:53

标签: ruby xml

我试图想出一种循环遍历此哈希的方法

students = {
  first: {ID: 1, UPN: "S535449032228", forename: "James", surname: "Penn", email: "jpenn@stanleypark.com", formerUPN: "S535449032229", gender: "Male", yearGroup: "Year 3", lang: "ENG"},
  second: {ID: 2,UPN: "K535449032230", forename: "Sandy", surname: "Snow", email: "ssnow@stanleypark.com", formerUPN: "K535449032231", gender: "Female", yearGroup: "Year 2", lang: "ENG"},
  third: {ID: 3, UPN: "J535449032230", forename: "Mike", surname: "Myers", email: "myers@stanleypark.com", formerUPN: "J535449032230", gender: "Male", yearGroup: "Year 5", lang: "ENG"},
  fourth: {ID: 4, UPN: "P535449032228", forename: "Penny", surname: "Dyer", email: "pdyer@stanleypark.com", formerUPN: "P535449032229", gender: "Female", yearGroup: "Year 4", lang: "ENG"},
  fith: {ID: 5, UPN: "D535449032230", forename: "Roger", surname: "Smith", email: "rogers@stanleypark.com", formerUPN: "D535449032231", gender: "Male", yearGroup: "Year 1", lang: "ENG"},
  sixth: {ID: 6, UPN: "E535449032230", forename: "Johnny", surname: "Johnson", email: "jjohnson@stanleypark.com", formerUPN: "E535449032230", gender: "Male", yearGroup: "Year 3", lang: "ENG"},
  seventh: {ID: 7, UPN: "S695449032228", forename: "Robert", surname: "Pennfold", email: "rpennfold@stanleypark.com", formerUPN: "S535449033229", gender: "Male", yearGroup: "Year 2", lang: "ENG"},
  eighth: {ID: 8, UPN: "R535449032230", forename: "Chelsey", surname: "Luigi", email: "chelluigi@stanleypark.com", formerUPN: "R535449032231", gender: "Female", yearGroup: "Year 4", lang: "ENG"}
}

并查找电子邮件中是否存在重复项,但是我遇到的问题是无法找出正确的方法来编写代码。

我想知道是否有人有任何可以尝试的建议?

我正在使用Nokogiri gem,因为我将创建一个xml文件,但希望首先检查重复项

2 个答案:

答案 0 :(得分:3)

考虑到哈希的结构,您可以执行以下操作:

$ sudo su - postgres
$ cd ~
$ nano .pgpass

# Insert the following text and save the document:
localhost:5432:*:postgres:[postgres_password]

$ chmod 0600 .pgpass

$ pgagent hostaddr=localhost dbname=postgres user=postgres

作为旁注:对于您的结构,使用数组而不是哈希更容易,因为# get all users emails as an array. _hash_key (first, second etc.) param is ignored emails = students.map { |_hash_key, student| student[:email] } # detect all emails which have more than one occurrence emails.select { |email| emails.count(email) > 1 }.uniq firstsecond等键没有多大意义而没有帮助您更轻松地编写程序代码。 third可以更轻松地循环播放您的数据。

Array

答案 1 :(得分:1)

students.values.group_by { |e| e[:email] }.count == students.count