1

I am trying to write a loop that takes in a nested array and makes a sub-array of two consecutive tuples at a time. The input array may be something like this

arr = [['A','B'],['C','D'],['E','F'],['G','H'],['I','J'],['K','L'],
      ['M','N'],['O','P']]

Output: ['A','B'],['C','D']
        ['E','F'],['G','H']
        ['I','J'],['K','L']
        ['M','N'],['O','P']

I have tried out various loops, like

arr.each_slice(2) do |k,m|
   new_arr=[k,m]
   puts new_arr
end 

and

 arr.each_slice(2) { |k,m| puts(k,m) }

What is wrong with this? In both the cases, the output is

A
B
C
D .....

1 Answer 1

5

That's just how puts is treating arrays in ruby 1.9, it prints each element on a new line. The result is what you want, it just looks differently when printed :) Try printing with .inspect, for example.

arr = [['A','B'],['C','D'],['E','F'],['G','H'],['I','J'],['K','L'],
      ['M','N'],['O','P']]

arr.each_slice(2) do |k,m|
   new_arr = [k,m]
   puts new_arr.inspect
end
# >> [["A", "B"], ["C", "D"]]
# >> [["E", "F"], ["G", "H"]]
# >> [["I", "J"], ["K", "L"]]
# >> [["M", "N"], ["O", "P"]]

http://www.ruby-doc.org/core-1.9.3/IO.html#method-i-puts

puts(obj, ...) → nil

Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.

$stdout.puts("this", "is", "a", "test")

produces:

this
is
a
test
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.