Displaying data into table form,

#1

col_arr = [“id”,“name”,“age”,“dept”]
values_arr = [[1,“sunil”,20,“IT”],
[2,“anil”,20,“IT”],
[3,“shiva”,25,“IT”],
[4,“guru”,23,“IT”] ]

so how can i display in the below formate

id name age dept
1 sunil 20 IT
2 anil 20 IT
3 shiva 25 IT
4 guru 23 IT

#2

Are you having problems with formatting the output or are you have problems with traversing the array?

#3

i have problems with formatting the output

#4

First of all, please use the code tag to write the code.
Otherwise it gets harder to copy paste your program, and I needed modify it.

Anyways, your code should look like this:

col_arr = %w(id name age dept)

values_arr = [
	[1,"sunil",20,"IT"],
	[2,"anil",20,"IT"],
	[3,"shiva",25,"IT"],
	[4,"guru",23,"IT"]
]

puts col_arr.join(?\s), values_arr.map { |x| x.join(?\s) }

Output:

id name age dept
1 sunil 20 IT
2 anil 20 IT
3 shiva 25 IT
4 guru 23 IT

If you want to indent the output with proper spaces:

col_arr = %w(id name age dept)

values_arr = [
	[1,"sunil",20,"IT"],
	[2,"anil",20,"IT"],
	[3,"shiva",25,"IT"],
	[4,"guru",23,"IT"]
]

all = [col_arr] + values_arr

spaces = all[0].size.times.map do |x|
	all.map { |y| y[x] }
end.map { |x| x.map { |y| y.to_s.length }.max }

puts col_arr.map.with_index { |x, i| x.ljust(spaces[i].next) }.join
puts values_arr.map { |x| x.map.with_index { |y, i| y.to_s.+(?\s).send(y.is_a?(Integer) ? :rjust : :ljust, spaces[i].to_i.next) }.join }

Output:

id name  age dept 
 1 sunil  20 IT   
 2 anil   20 IT   
 3 shiva  25 IT   
 4 guru   23 IT  

This is not slow, works nicely, but I know I write ugly code!


Hope this helps!

#5

Thank you! so much. both codes are working fine