當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Ruby Array zip()用法及代碼示例


Array#zip():zip()是一個Array類方法,它將任何參數轉換為數組,然後將self元素與每個參數中的對應元素合並。

用法:Array.zip()

參數:數組


返回:將self元素與每個參數中的對應元素合並。

示例1:

# Ruby code for zip() method 
  
# declaring array 
a = [18, 22, 33, nil, 5, 6] 
  
# declaring array 
b = [1, 4, 1, 1, 88, 9] 
  
# declaring array 
c = [18, 22, 50, 6] 
  
  
# zip method example 
puts "zip() method form : #{a.zip(b)}\n\n"
  
puts "zip() method form : #{b.zip(c)}\n\n"
  
puts "zip() method form : #{c.zip(c)}\n\n"

輸出:

zip() method form : [[18, 1], [22, 4], [33, 1], [nil, 1], [5, 88], [6, 9]]

zip() method form : [[1, 18], [4, 22], [1, 50], [1, 6], [88, nil], [9, nil]]

zip() method form : [[18, 18], [22, 22], [50, 50], [6, 6]]

示例2:

# Ruby code for zip() method 
  
# declaring array 
a = ["abc", "nil", "dog"] 
  
# declaring array 
c = ["cat", nil] 
  
# declaring array 
b = ["cow", nil, "dog"] 
  
  
# zip method example 
puts "zip() method form : #{a.zip(b)}\n\n"
  
puts "zip() method form : #{b.zip(c)}\n\n"
  
puts "zip() method form : #{c.zip(c)}\n\n"

輸出:

zip() method form : [["abc", "cow"], ["nil", nil], ["dog", "dog"]]

zip() method form : [["cow", "cat"], [nil, nil], ["dog", nil]]

zip() method form : [["cat", "cat"], [nil, nil]]



相關用法


注:本文由純淨天空篩選整理自mayank5326大神的英文原創作品 Ruby | Array zip() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。