David Chu
David Chu

Reputation: 13

Having an issue with iterating output to a certain way

I am practicing using arrays and iteration in Ruby. I was able to understand the context of the code but I am having a problem displaying the output a certain way.

My expected output is:

0 0 0 0
0 1 0 0 
0 0 0 1
0 0 0 0 

The current output is:

0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0

My code is:

class Image
  def initialize(image)
    @image = image
  end

  def output_image
    @image.each_index do |array|
      subarray = @image[array]
      subarray.each do |cell|
        if array[0]
          print "#{cell} \n"
        elsif array[1]
          print "#{cell} \n"
        elsif array[2]
          print "#{cell} \n"
        elsif array[3]
          print "#{cell} \n"
        end
      end
    end
  end
end

image = Image.new([
  [0, 0, 0, 0],
  [0, 1, 0, 0],
  [0, 0, 0, 1],
  [0, 0, 0, 0]
 ])

 image.output_image

Upvotes: 0

Views: 41

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Array#join comes to the rescue here. Join rows with a space, join result with a carriage return, profit.

puts @image.map { |inner| inner.join ' ' }.join $/
#⇒ 0 0 0 0
#  0 1 0 0
#  0 0 0 1
#  0 0 0 0

Upvotes: 1

Eyeslandic
Eyeslandic

Reputation: 14890

You're making this unnecessarily complicated for you I think. You can just iterate over the sub arrays and join them with a space.

def output_image
  @image.each do |image|
    puts image.join(' ')
  end
end

Upvotes: 1

Related Questions