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

时间:2013-12-20 13:42:13

标签: ruby

我对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.

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

4 个答案:

答案 0 :(得分:2)

使用Array#zipArray#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.

答案 1 :(得分:2)

仅仅{p> each是不够的。将其与transpose结合使用。

[titles, *data]
.transpose.each{|title, *datum| puts "#{title}: #{datum.join(", ")}"}

答案 2 :(得分:0)

简单的方法:

names = []
addresses = []
descriptions = []
data.each do |ele|
  names << ele.first
  addresses << ele.second
  descriptions << ele.last  
end

puts "#{titles[0]}: #{names.join(', ')}"
puts "#{titles[1]}: #{addresses.join(', ')}"
puts "#{titles[2]}: #{descriptions.join(', ')}"

答案 3 :(得分:0)

您可以映射数据数组以获取相关数据,然后使用Array#join将它们全部连接成一个字符串。

titles = data.map.each { |d| d[0] }
addresses = data.map.each { |d| d[1] }
description = data.map.each { |d| d[2] }

puts "Name: #{titles.join(', ')}"
puts "Address: #{addresses.join(', ')}"
puts "Description: #{description.join(', ')}"