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


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


Ruby中的assoc()函數用於搜索其第一個元素與該函數的索引進行比較的數組數組,如果找到匹配項,則返回包含的數組,否則返回nil或vacant。

用法: Array.assoc(Object)
Here Array is the array of arrays.

參數:
Object :它是一個與包含的數組的第一個元素進行比較的元素。


返回值:如果找到匹配項,則包含的數組否則將返回nil或vacant。

示例1:

# Initializing a array of elements 
Array1 = ["Alphabets", "a", "b", "c", "d", "e"] 
Array2 = ["Names", "gfg", "Geeks", "Geek", "GeeksforGeeks"] 
Array3 = ["City", "Kolkata", "Mumbai", "Delhi", "Patna"] 
  
# Creating an array of above arrays 
Array = [Array1, Array2, Array3] 
  
# Calling assoc() function 
A = Array.assoc("Alphabets") 
B = Array.assoc("City") 
C = Array.assoc("Names") 
  
# Printing the matched contained array 
puts "#{A}"
puts "#{B}"
puts "#{C}"

輸出:

["Alphabets", "a", "b", "c", "d", "e"]
["City", "Kolkata", "Mumbai", "Delhi", "Patna"]
["Names", "gfg", "Geeks", "Geek", "GeeksforGeeks"]

示例2:

# Initializing a array of elements 
Array1 = ["Alphabets", "a", "b", "c", "d", "e"] 
Array2 = ["Names"] 
Array3 = "City"
  
# Creating an array of above arrays 
Array = [Array1, Array2, Array3] 
  
# Calling assoc() function 
A = Array.assoc("Alphabets") 
B = Array.assoc("City") 
C = Array.assoc("Names") 
  
# Printing the matched contained array 
puts "#{A}"
puts "#{B}"
puts "#{C}"

輸出:

["Alphabets", "a", "b", "c", "d", "e"]

["Names"]

參考: https://devdocs.io/ruby~2.5/array#method-i-assoc



相關用法


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