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 "-----"
EDIT: I love that I'm still receiving responses to this over 6 years later. Keep 'em coming!
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