Ruby 数组assoc()函数
Ruby中的assoc()函数用于搜索一个数组,该数组的第一个元素与函数的索引进行比较,如果发现匹配,则返回包含的数组,否则返回nil或vacant。
语法: Array.assoc(Object)
这里 Array 是数组的数组。
参数:
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