您可以對此使用並行分配,例如, a,b = b,a
。作爲一個方面說明,while
循環在Ruby中很少使用,因此將它視爲一個新手。更類似Ruby的方法是使用像times
,upto
,downto
等的枚舉數,它將很方便地提供指數i
和j
作爲循環變量。當你將這些方法存儲在Array類中時,你可以節省一次又一次地輸入matrix
,因爲你已經在課堂上了。此外,首先編寫一個增變器方法(改變原始對象,通常在方法名稱末尾通常用砰砰聲!
表示),然後編寫一個額外的非增變器方法,該方法簡單地調用複製器上的增變器。這是我會怎麼寫代碼:
class Array
def my_transpose!
size.times do |i|
0.upto(i) do |j| # iterate only through lower half
self[i][j], self[j][i] = self[j][i], self[i][j] # swap rows and cols
end
end
self # return the array itself
end
def my_transpose
dup.map(&:dup).my_transpose! # inner arrays are dup'ed, too
end
end
有趣的是,Ruby的內置transpose
不能作爲賦值函數。以下是如何使用上面的代碼:
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
a.my_transpose! # mutator
#=> [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
a
#=> [[1, 1, 1], [2, 2, 2], [3, 3, 3]] # note that a changed
a.my_transpose!
#=> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
a
#=> [[1, 2, 3], [1, 2, 3], [1, 2, 3]] # a is back to its original state
a.my_transpose # non-mutator
#=> [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
a
#=> [[1, 2, 3], [1, 2, 3], [1, 2, 3]] # note that a did not change
爲什麼不簡單地使用從陣列轉置? – vgoff
FYI Rubinius有一個純Ruby實現:https://github.com/rubinius/rubinius/blob/master/kernel/common/array.rb#L1623 – Stefan