2013-12-20 2 views
1

저는 Ruby를 처음 사용합니다. 나는이 도전을 시도하고 붙어있어. 다음과 같은 배열을 감안할 때 Ruby - 다른 배열의 각 요소에 액세스

:

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 }하지만 I : 지금은

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.']] 

, 나는 이런 식으로 뭔가를 인쇄하고 싶습니다 조직적 방법으로 다른 배열에서 해당 요소에 액세스하는 것을 후속 조치 할 수 없습니다. 이 문제에 대해 .each이면 충분합니까?

답변

2

사용 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. 
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(', ')}" 
0

당신은 관련 데이터에 대한 데이터 배열을지도하고 배열 번호를 사용할 수 있습니다 그것들을 모두 문자열로 연결하기 위해 결합하십시오.

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(', ')}" 
2

만으로는 충분하지 않습니다. 그것을 transpose와 결합하십시오.

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