1

I am fairly new to Ruby. I am attempting this challenge and got stuck.

Given the following arrays:

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

For now, I would like to print something like this:

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.

As far as my limited knowledge goes, I have attempted titles.each { |title| print title } but I cannot follow up accessing its respective elements from another array in a methodical way. Is .each sufficient for this problem?

4 Answers 4

2

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

prints

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.
Sign up to request clarification or add additional context in comments.

Comments

2

each alone is not enough. Combine it with transpose.

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

Comments

0

You could map your data array for the relevant data and then use Array#join to concatenate them all into a string.

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

Comments

0

Little simpler approach:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.