user1762229
user1762229

Reputation: 71

placing sub arrays in neat rows

I am currently working on a large array of names:

large_array = ["Bob","Joel","John","Smith","Kevin","Will","Stanley","George"] #and so on

I split it into sub arrays like so:

large_array.each_slice(2).to_a #=> [["Bob", "Joel"],["John,"Smith"],["Kevin", "Will"],["Stanley","George"]]

My question is how do I make the sub arrays appear neatly on top of each other in rows like this:

["Bob", "Joel"]
["John,"Smith"]
["Kevin","Will"]
["Stanley","George"]

Upvotes: 0

Views: 112

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

You call that "neat"? This is what I call "neat":

enum = large_array.each_slice(2)
fname_max = enum.map { |f,_| f.size }.max + 3
lname_max = enum.map { |_,l| l.size }.max + 1

enum.each { |f,l|
  puts "[\"#{ (f+'",').ljust(fname_max) }\"#{ (l+'"').ljust(lname_max) }]" }
  #-> ["Bob",     "Joel"  ]
  #   ["John",    "Smith" ]
  #   ["Kevin",   "Will"  ]
  #   ["Stanley", "George"]

Here's another way to write your "neat":

enum = large_array.to_enum
loop do
  puts [enum.next, enum.next].to_s
end
  #-> ["Bob", "Joel"]
  #   ["John", "Smith"]
  #   ["Kevin", "Will"]
  #   ["Stanley", "George"]

This works fine for "large" arrays, but for "huge" arrays (more than eight elements), you may wish to change the operative line to:

puts [enum.next, enum.next].to_s.tinyfy

for display purposes. That will print the following:

   ["Bob", "Joel"]
   ["John", "Smith"]
   ["Kevin", "Will"]
   ["Stanley", "George"]

Upvotes: 0

maerics
maerics

Reputation: 156434

large_array.each_slice(2) {|a| puts a.inspect}
# ["Bob", "Joel"]
# ["John", "Smith"]
# ["Kevin", "Will"]
# ["Stanley", "George"]
# => nil

Upvotes: 2

Related Questions