以下是member和member_email详细信息:
- @members.each do |member|
- member.member_emails.each do |member_email|
- email_hash = { member.id.to_s => { member_email.kind => member_email.email } }
如果已存在密钥,如何附加哈希? 获取email_hash的结果是:
{"6"=>{"personal"=>"abc@gmail.com"}}
{"4"=>{"work"=>"def@yahoo.com"}}
{"4"=>{"personal"=>"xyz@gmail.com"}}
预期结果是:
{"6"=>{"personal"=>"abc@gmail.com"}}
{"4"=>{"work"=>"def@yahoo.com", "personal"=>"xyz@gmail.com"}}
非常感谢任何帮助。谢谢!
答案 0 :(得分:1)
我不完全确定你要做什么(不知道上下文)但是现在,你正在循环member.member_emails
并为每个电子邮件。假设您想为每个用户创建一个哈希,您可以执行以下操作:
- @members.each do |member|
- email_hash = {}
- member.member_emails.each do |member_email|
- email_hash[member_email.kind] = member_email.email
- user_hash = { member.id.to_s => email_hash }
答案 1 :(得分:0)
尝试:
假设值是哈希值。
def add_or_append(hash, key, value)
if hash[key]
hash[key].merge(value)
else
hash[key] = value
end
end
如果value是字符串:
def add_or_append(hash, key, value)
if hash[key]
hash[key] << ", #{value}"
else
hash[key] = value
end
end