Ruby入门迭代问题求助:批量为哈希元素生成符合要求的邮箱字段
问题分析
- 你当前仅提取了所有姓名到独立数组,但最终仅访问了索引为0的第一个元素,没有遍历全部3个元素生成邮箱
- 生成的邮箱没有插入到
people数组对应位置的哈希中,没有实现预期的新增email字段的效果
修改后的完整代码
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 while outer_index < people.length # 取出当前遍历的个人哈希 current_person = people[outer_index] # 按规则生成邮箱 email = current_person["first_name"].downcase + current_person["last_name"].downcase + "@gmail.com" # 给当前哈希新增email字段 current_person["email"] = email outer_index += 1 end # 按作业要求结尾输出 p people
关键逻辑说明
- 不需要单独把所有姓名存到额外数组,直接在遍历
people的循环中操作对应索引的个人哈希即可 - 循环会自动依次处理索引0、1、2对应的三个人的信息,逐个生成邮箱并插入对应哈希
- Ruby的哈希可以直接通过
哈希变量[新键名] = 新值的方式新增字段
内容的提问来源于stack exchange,提问作者Philip Jobe
相关产品推荐
相关产品推荐

