gpt4 book ai didi

Ruby - 从另一个数组访问相应的元素

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:56 25 4
gpt4 key购买 nike

我是 Ruby 的新手。我正在尝试这个挑战,但卡住了。

给定以下数组:

titles = ['Name', 'Address', 'Description']

data = [['Reddit', 'www.reddit.com', 'the frontpage of the internet'],
['Wikipedia', 'en.wikipedia.net', 'The Free Encyclopedia'],
['xkcd', 'xkcd.com', 'Sudo make me a sandwich.']]

现在,我想打印这样的东西:

Name: Reddit, Wikipedia, xkcd
Address: www.reddit.com, en.wikipedia.net, xkcd.com
Description: the frontpage of the internet, The Free Encyclopedia, Sudo make me a sandwich.

就我有限的知识而言,我尝试过标题.each { |标题| print title 但我无法以有条不紊的方式从另一个数组访问其各自的元素。 .each 是否足以解决这个问题?

最佳答案

使用Array#zip , Array#transpose :

titles = ['Name', 'Address', 'Description']
data = [
['Reddit', 'www.reddit.com', 'the frontpage of the internet'],
['Wikipedia', 'en.wikipedia.net', 'The Free Encyclopedia'],
['xkcd', 'xkcd.com', 'Sudo make me a sandwich.']
]

titles.zip(data.transpose()) { |title, data|
puts "#{title} #{data.join(', ')}"
}

打印

Name Reddit, Wikipedia, xkcd
Address www.reddit.com, en.wikipedia.net, xkcd.com
Description the frontpage of the internet, The Free Encyclopedia, Sudo make me a sandwich.

关于Ruby - 从另一个数组访问相应的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20704952/

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