红宝石 |数组 assoc()函数
Ruby 中的 assoc()函数用于搜索数组数组,其第一个元素与函数的索引进行比较,如果找到匹配则返回包含的数组,否则返回 nil 或空置。
Syntax: Array.assoc(Object)
Here Array is the array of arrays.
Parameters:
Object : It is an element which gets compared with the first element of the contained array.
Returns: the contained array if match found otherwise returns either nil or 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