ruby - Printing multiple arrays in one line -
i'm trying print several arrays on 1 line. first line ok loop breaks down after that. i've tried going on serveral times no cigar. here's code:
chapter_num = ['chapter 1', 'chapter 2', 'chapter 3'] chapter_title = ['numbers', 'letters', 'variables'] chapter_page = ['page 1', 'page 72', 'page 118'] #prints chapter number chapter_num.each |num| print (num.ljust 0) #prints title chapter_title.each |title| print (title.center 14) #prints page number chapter_page.each |page| puts (page.rjust 40) end end end
when run above code looks this:
chapter 1 numbers page 1 page 72 page 118 letters page 1 page 72 page 118 variables page 1 page 72 page 118 chapter 2 numbers page 1 page 72 page 118 letters page 1 page 72 page 118 variables page 1 page 72 page 118 chapter 3 numbers page 1 page 72 page 118 letters page 1 page 72 page 118 variables page 1 page 72 page 118
it's suppose this:
chapter 1 numbers page 1 chapter 2 letters page 72 chapter 3 variables page 118
you use array::zip
method here:
chapter_num = ['chapter 1', 'chapter 2', 'chapter 3'] chapter_title = ['numbers', 'letters', 'variables'] chapter_page = ['page 1', 'page 72', 'page 118'] arr = chapter_num.zip(chapter_title, chapter_page) arr.each { |el| puts "#{el[0].ljust 0} #{el[1].center 14} #{el[2].rjust 40}" } #=> chapter 1 numbers page 1 #=> chapter 2 letters page 72 #=> chapter 3 variables page 118
and--since array::zip
takes optional block--you in 1 line:
chapter_num.zip(chapter_title, chapter_page).each { |el| puts "#{el[0].ljust 0} #{el[1].center 14} #{el[2].rjust 40}" }
Comments
Post a Comment