【问题标题】:I for some reason can't get this iteration thing right in my head由于某种原因,我无法在脑海中正确地理解这个迭代
【发布时间】:2021-11-08 07:01:07
【问题描述】:

再一次,我是整个计算机编码的新手,我正在做一个新兵训练营,试图掌握基础知识并踏上第一步,但由于某种原因,我无法让整个迭代的事情坚持下去我的大脑,我们刚刚开始在 ruby​​ 中进行哈希计算,而我实际上已经盯着检查点问题看了一天半,我只是无法让我的大脑知道下一个合乎逻辑的步骤是什么才能得到提供的答案。它在几周后我的实际现场课程开始之前的工作前部分,而且这只是我第二个完整的一周进行任何编码,所以最简单的基本提示/答案将不胜感激。

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

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"
   }
]

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

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

【问题讨论】:

  • 计算的电子邮件需要添加回用于计算它的散列中,这将发生在循环内,对于每个数组元素(“散列”)。请注意,您可能会得到使用更规范的 Ruby 代码的答案。

标签: ruby iteration


【解决方案1】:

循环遍历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

【讨论】:

  • 你忘记小写了。
  • 谢谢你,我明天会回到它并尝试退出复杂化它。
【解决方案2】:

你真的太复杂了,没有必要使用 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

【讨论】:

  • 谢谢你,我明天会回到它,并尝试退出在我的脑海中复杂化它
  • @PhilipJobe 请记住,Ruby 是高级面向对象的语言,您可以通过调用对象的方法来解决问题。 whileuntilloop 等相关结构主要用于处理用户输入或流。花一些时间牢记 Enumerable 上的方法 - 它会带来巨大的回报。
猜你喜欢
  • 2018-06-16
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多