gpt4 book ai didi

ruby-on-rails - Ruby 将两个数组合并为一个

转载 作者:数据小太阳 更新时间:2023-10-29 06:29:20 27 4
gpt4 key购买 nike

这是我的情况。我有 2 个数组

@names = ["Tom", "Harry", "John"]

@emails = ["tom@gmail.com", "h@gmail.com", "j@gmail.com"]

我想将这两个组合成一些名为 @list 的 Array/Hash,这样我就可以在我的 View 中像这样迭代:

<% @list.each do |item| %>
<%= item.name %><br>
<%= item.email %><br>
<% end %>

我无法理解如何实现这个目标。有什么想法吗?

最佳答案

@names  = ["Tom", "Harry", "John"]
@emails = ["tom@gmail.com", "h@gmail.com", "j@gmail.com"]

@list = @names.zip( @emails )
#=> [["Tom", "tom@gmail.com"], ["Harry", "h@gmail.com"], ["John", "j@gmail.com"]]

@list.each do |name,email|
# When a block is passed an array you can automatically "destructure"
# the array parts into named variables. Yay for Ruby!
p "#{name} <#{email}>"
end
#=> "Tom <tom@gmail.com>"
#=> "Harry <h@gmail.com>"
#=> "John <j@gmail.com>"

@urls = ["yahoo.com", "ebay.com", "google.com"]

# Zipping multiple arrays together
@names.zip( @emails, @urls ).each do |name,email,url|
p "#{name} <#{email}> :: #{url}"
end
#=> "Tom <tom@gmail.com> :: yahoo.com"
#=> "Harry <h@gmail.com> :: ebay.com"
#=> "John <j@gmail.com> :: google.com"

关于ruby-on-rails - Ruby 将两个数组合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4572992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com