我正在嘗試壓縮3個變數,因為我在3個不同的陣列上回圈,但是資料型別被扭曲了,即使我可以列印變數,它們也是一樣的,只是它們最后變成了陣列或其他資料型別。(如果我列印l1而不是l1.class,我就會得到正確的輸出)
a = [1,2,3]
b = [1,2, 3]
c = ['a'/span>,'b'/span>,'c'/span>]
那么
a.zip(b).each do |l1,l2|
將l1.class, l2.class放進l1.class中。
end。
給出了:
Integer
整數
整數
整數
整數
整數
很好! BUT
a.zip(b).zip(c).each do |l1,l2,l3|
將l1.class, l2.class, l3.class.
end
給出了
Array
字串
無類
陣列
字串
無類
陣列
弦樂
無類
我如何壓縮這3個變數,保持它們的型別?
謝謝你!
uj5u.com熱心網友回復:
e = a.zip(b)
#=> [[1, 1], [2, 2], [3, 3]]/span>
e.zip(c)
#=> [[[1, 1], "a"], [[2, 2], "b"], [[3, 3], "c"]]
顯示了這個問題。見Array#zip。
這里有三種方法可以獲得預期的結果。全部列印
Integer
整數
字串
整數
整數
編碼
整數
整數
弦樂
a.zip(b,c).each { |arr| puts *arr.map(& :class) }
注意
a.zip(b,c)
#=> [[1, 1, "a"], [2, 2, "b"], [3, 3, "c"]]/span>
如果去掉splat運算子(*),就會列印出以下內容:
[Integer, Integer, String]。
[整數, 整數, 字串]
[整數,整數,字串] [整數,整數,字串
a.each_index { |i| puts a[i]. class, b[i].class, c[i].class }
#=> [1,2,3]
[a.map(&:class), b.map(&:class), c.map(&:class)]
.轉置
.each { |r| puts *r }
#=> [[Integer, Integer, String],
# [Integer, Integer, String],
# [Integer, Integer, String]]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/323811.html
標籤:
