我是 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.
我是一名优秀的程序员,十分优秀!