I've been stuck on this for a while. As an assignment I need to transpose this 2D array without using the built in transpose method, and without altering the function name / output. I feel like it should be way easier than I'm making it out to be...
class Image
def transpose @array.each_with_index do |row, row_index| row.each_with_index do |column, col_index| @array[row_index] = @array[col_index] end end end
end
image_transpose = Image.new([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print "Image transpose"
puts
image_transpose.output_image
puts "-----"
image_transpose.transpose
image_transpose.output_image
puts "-----" 1 2 Answers
Try below code:
class Image def initialize(array) @array = array end def transpose _array = @array.dup @array = [].tap do |a| _array.size.times{|t| a << [] } end _array.each_with_index do |row, row_index| row.each_with_index do |column, col_index| @array[row_index][col_index] = _array[col_index][row_index] end end end
end
image_transpose = Image.new([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
image_transpose.transpose 4 I suggest you replace the method transpose with the following.
def transpose @array.first.zip(*@array[1..-1])
endThe need for the (undefined) method output_input is not evident. You will also need an initialize method, of course, to assign a value to the instance variable @array.
I assume you are being asked to improve upon the implementation of the method transpose; otherwise there would be no reason for the stipulation that you cannot use Ruby's built-in transpose method.