Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing an array of arrays on one line in console (one line per master array object) in Ruby

Tags:

arrays

ruby

I have an array of arrays that is currently printing each object in the array on its own line. The master array holds many different people inside of it. Each person has 5 different objects stored to them (e.g. Last Name, First Name, DOB.. etc)

Kournikova
Anna
F
6/3/1975
Red

Hingis
Martina
F
4/2/1979
Green

Seles
Monica
F
12/2/1973
Black

What I'm trying to do is print out each person and their corresponding objects on one line, per person.

Does anyone have a solution for this? Additionally, the output should not contain array brackets ([]) or commas. I'm wondering if it will simply need to be a string, or if there is something I am missing.

Some of my code below:

space_array = [split_space[0],split_space[1],split_space[3],new_date,split_space[5]]
master << space_array 
puts master

The ideal output would be something like this:

Kournikova Anna F 6/3/1975 Red
Hingis Martina F 4/2/1979 Green
Seles Monica F 12/2/1973 Black
like image 959
tandy Avatar asked Mar 15 '12 19:03

tandy


People also ask

How do I print an array on one line?

Print Array in One Line with Java StreamsArrays. toString() and Arrays. toDeepString() just print the contents in a fixed manner and were added as convenience methods that remove the need for you to create a manual for loop.

How do you print an array of arrays?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.

How do you print an array in Ruby?

Ruby printing array contentsThe array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.

How do you print each element of an array to a different line?

How do you print an array of elements in a new line in Python? Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by comma use sep=”\n” or sep=”, ” respectively.


2 Answers

your_array.each do |person|
  puts person.join(" ")
end
like image 57
Andrei S Avatar answered Sep 28 '22 10:09

Andrei S


The method puts will automatically put a new line. Use print instead to print the text out with no new line.

Or if you want, you can use the join function.

['a', 'b', 'c'].join(' ') 
=> 'a b c'
like image 39
Rob Taylor Avatar answered Sep 28 '22 10:09

Rob Taylor