Faker gem not creating unique data when pushed into array loop

时间:2018-02-03 10:34:28

标签: arrays ruby xml

so I am trying to push a hash that I have created into an array while making 5 fields of fake data, but I am running into issues where when I call the variable through the loop it display's unique data, when I call the whole array outside, every singe field is filled with the same data.

I can't figure it out, is anyone able to help? Here is my code

  students = Nokogiri::XML(File.open(file))
  names = students.css("Forename").map              { |node| node.children.text }
  mis_id = students.css("MIS_ID").map               { |node| node.children.text }
  gender = students.css("Gender").map               { |node| node.children.text }
  yearGroup = students.css("YearGroup").map         { |node| node.children.text }
  firstLanguage = students.css("FirstLanguage").map { |node| node.children.text }

  pupils = [
    {ID: nil, UPN: "", forename: "", surname: "", email: "", formerUPN: "", gender: "", yearGroup: "", lang: ""}
  ]

  student = pupils.first
  pupils.shift

  names.each { |name|
    name = Faker::Name.first_name

    student[:forename]  = name
    student[:surname]   = Faker::Name.last_name
    student[:UPN]       = Faker::Code.ean
    student[:formerUPN] = Faker::Code.ean
    student[:email]     = Faker::Internet.unique.email

    pupils << student


  }

Through the loop if I output the variable "student" it returns each hash but all the filled in fields are unique e.g. Forename, surname, UPN etc...

but when I display the pupils, all the fields are saved as the same, instead of unique, I have been trying for the last few hours and need some advice.

1 个答案:

答案 0 :(得分:2)

You have encountered this problem because you are creating new student through each iteration, but you are just pushing the reference for that new student instead of its value. As a result, your pupils array will contain identical elements, which will have the value of student from the last iteration.

I suggest you to use Ruby's built-in clone method to create shallow copy of your student hash in each iteration and push that copy into your students array.

pupils << student.clone

Hope this helps you.