0

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"]
user1762229
  • 71
  • 1
  • 6

2 Answers2

2
large_array.each_slice(2) {|a| puts a.inspect}
# ["Bob", "Joel"]
# ["John", "Smith"]
# ["Kevin", "Will"]
# ["Stanley", "George"]
# => nil
maerics
  • 151,642
  • 46
  • 269
  • 291
  • when I run it I'm getting the code you have up there, but instead of nil I also get #=> ["Bob","Joel","John","Smith","Kevin","Will","Stanley","George"] is there a way to get rid of that last combined array? @maerics – user1762229 Apr 07 '15 at 16:33
  • @user1762229, yes, just add a semicolon to then end of the statement. `large_array.each_slice(2) {|a| puts a.inspect};`. – Mori Apr 07 '15 at 16:45
  • Readers: `Array#to_s` is an alias of `Array#inspect`. This could be written `puts large_array.each_slice(2).map(&:inspect)`, but that has the disadvantage of creating a temporary array. maerics, OP doesn't want a closing quote after 'John`. :-) – Cary Swoveland Apr 07 '15 at 17:31
0

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"]
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100