我出于某种原因无法正确理解这个迭代的事情

I for some reason can't get this iteration thing right in my head

再一次,我是整个计算机编码领域的新学生,我正在参加新手训练营以尝试获得基础知识并踏入大门,但由于某种原因我无法进行整个迭代请记住,我们刚刚开始在 ruby 中进行哈希运算,我实际上已经盯着检查点问题看了一天半了,我只是无法让我的大脑知道下一个合乎逻辑的步骤是什么提供的答案。它在几周后我的实际生活 类 开始之前的工作前部分,这只是我第二个整周进行任何编码所以最基本的基本 hints/answers 将不胜感激。

问题是这样的: 编写一个循环,为每个人提供一个电子邮件地址,该地址由他们的名字 + 姓氏 @ gmail.com 组成。例如,Robert Garcia 的电子邮件地址为 robertgarcia@gmail.com。该程序应以:p people

people = [
  {
    "first_name" => "Robert",
    "last_name" => "Garcia", 
    "hobbies" => ["basketball", "chess", "phone tag"]
   },
   {
    "first_name" => "Molly",
    "last_name" => "Barker",
    "hobbies" => ["programming", "reading", "jogging"]
   },
   {
    "first_name" => "Kelly",
    "last_name" => "Miller",
    "hobbies" => ["cricket", "baking", "stamp collecting"]
   }
]

outer_index = 0
names = []
last_names = []
while outer_index < people.length
  names << people[outer_index]["first_name"].downcase
  last_names << people[outer_index]["last_name"].downcase
  outer_index += 1
end 


  email = email = [names[0] + last_names[0] + "@gmail.com"]

这是我取得的所有进展,因为我试图让它回到低谷并拿起第二个和第三个名字的一切都没有奏效。

根据他们的说法,最终应该是这样的: 这样您就可以查看是否对每个哈希进行了正确的修改。结果应该是:

people =[
  {
    "first_name" => "Robert",
    "last_name" => "Garcia", 
    "hobbies" => ["basketball", "chess", "phone tag"],
    "email" => "robertgarcia@gmail.com"
   },
   {
    "first_name" => "Molly",
    "last_name" => "Barker",
    "hobbies" => ["programming", "reading", "jogging"],
    "email" => "mollybarker@gmail.com"
   },
   {
    "first_name" => "Kelly",
    "last_name" => "Miller",
    "hobbies" => ["cricket", "baking", "stamp collecting"],
    "email" => "kellymiller@gmail.com"
   }
]

(请注意,您的输出不会很好地缩进)。

我完全不知所措,我看不出哪里出了问题,所以任何帮助都会非常有帮助,这样我就可以通过这个检查点并完成第二周并尽快进入第三周。

遍历 people 数组的每个元素非常简单。我们也可以使用字符串插值来轻松组成电子邮件地址。

people.each do |h| 
    h["email"] = "#{h["first_name"]}#{h["last_name"]}@gmail.com".downcase 
end

如果我们想稍微分解一下,我们可以。

people.each do |h| 
    fn = h["first_name"]
    ln = h["last_name"]
    h["email"] = "#{fn}#{ln}@gmail.com"
    h["email"].downcase!
end

你真的太复杂了,没有必要使用 while 来简单地遍历数组。而是使用 the Enumerable module:

中的 #each
people.each do |hash|
  hash.merge!(
    "email" => "#{hash['first_name']}#{hash['last_name']}@gmail.com".downcase
  )
end

或者,如果您想要一个不改变原始数据的非破坏性版本:

people.map do |hash|
  hash.merge(
    "email" => "#{hash['first_name']}#{hash['last_name']}@gmail.com".downcase
  )
end