Displaying data into table form,

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

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

i have problems with formatting the output

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,"sunila",20,"IT"],
	[2,"anil",20,"IT"],
	[3,"shiva",25,"IT"],
	[4,"guru",23,"IT"]
]

spaces = [col_arr, *values_arr].transpose.map! { |x| x.map! { |y| y.to_s.length }.max }

puts col_arr.map!.with_index { |x, i| x.ljust(spaces[i].next) }.join,
	values_arr.map { |x| x.map!.with_index { |y, i| y.to_s.+(?\s.freeze).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!

Thank you! so much. both codes are working fine

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs