Array.zip() 方法
在本文中,我們將研究 Array.zip() 方法。你們一定認為該方法必須做一些與壓縮 Array 實例的值相關的事情。它並不像看起來那麽簡單。好吧,我們將在其餘內容中解決這個問題。我們將嘗試借助語法和演示程序代碼來理解它。
方法說明:
此方法是一個公共實例方法,是為 Ruby 庫中的 Array 類定義的。此方法的用法方式是將任何參數轉換為 Array 對象,然後將該 Array 實例與 self 數組的元素合並。這會產生一個 Array.length n-element Array 對象的序列,其中 n 可能大於元素的數量。如果任何參數的大小小於初始數組的大小,該方法將提供 "nil" 值。如果您提供一個塊,則為每個結果數組對象調用該塊,否則返回一個數組數組,或者您可以說返回一個多維數組。
用法:
array_instance.zip(arg, ...) -> new_ary array_instance.zip(arg, ...) { |arr| block } -> nil
所需參數:
此方法可以將多個對象作為參數。
範例1:
=begin
Ruby program to demonstrate zip method
=end
# array declaration
table = ["fatima","Sabita","Monica","Syresh","Kamish","Punish"]
table1 = ["Apple","Banana","Orange","Papaya"]
puts "Array zip implementation:"
puts "#{["abc","pqr"].zip(table,table1)}"
puts "Array instance:#{table}"
輸出
Array zip implementation: [["abc", "fatima", "Apple"], ["pqr", "Sabita", "Banana"]] Array instance:["fatima", "Sabita", "Monica", "Syresh", "Kamish", "Punish"]
說明:
在上麵的代碼中,您可以看到我們在 Array.zip() 方法的幫助下壓縮了 Array 對象。此方法是一種非破壞性方法,不會在實際 Array 實例中創建任何更改。
範例2:
=begin
Ruby program to demonstrate zip method
=end
# array declaration
table = ["fatima","Sabita","Monica","Syresh","Kamish","Punish"]
table1 = ["Apple","Banana","Orange","Papaya"]
puts "Array zip implementation:"
puts "#{table.zip(["Kuber","Kamesh"],table1)}"
puts "Array instance:#{table}"
輸出
Array zip implementation: [["fatima", "Kuber", "Apple"], ["Sabita", "Kamesh", "Banana"], ["Monica", nil, "Orange"], ["Syresh", nil, "Papaya"], ["Kamish", nil, nil], ["Punish", nil, nil]] Array instance:["fatima", "Sabita", "Monica", "Syresh", "Kamish", "Punish"]
說明:
在上麵的代碼中,您可以看到我們在 Array.zip() 方法的幫助下壓縮了 Array 對象。此方法是一種非破壞性方法,不會在實際 Array 實例中創建任何更改。
相關用法
- Ruby Array.reject用法及代碼示例
- Ruby Array.repeated_permutation()用法及代碼示例
- Ruby Array.index()用法及代碼示例
- Ruby Array.pack()用法及代碼示例
- Ruby Array.rassoc(obj)用法及代碼示例
- Ruby Array.values_at()用法及代碼示例
- Ruby Array.each用法及代碼示例
- Ruby Array.sort用法及代碼示例
- Ruby Array.unshift()用法及代碼示例
- Ruby Array.reverse用法及代碼示例
- Ruby Array.rotate()用法及代碼示例
- Ruby Array.repeated_combination()用法及代碼示例
- Ruby Array.replace()用法及代碼示例
- Ruby Array.drop_while用法及代碼示例
- Ruby Array.sort_by用法及代碼示例
- Ruby Array.shift用法及代碼示例
- Ruby Array.assoc(obj)用法及代碼示例
- Ruby Array.permutation()用法及代碼示例
- Ruby Array.join()用法及代碼示例
- Ruby Array.delete_if用法及代碼示例
注:本文由純淨天空篩選整理自 Array.zip() Method with Example in Ruby。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。