assoc()
Ruby中的功能到目前为止,我们已经研究了处理一维数组的assoc()
函数,但是如果我们谈论函数,则它不适用于一维数组。assoc()
函数仅适用于数组数组,或者可以说它适用于多维数组。该assoc()
方法的目的是检查每个数组的第一个元素。它通过使用指定的索引元素检查数组的第一个元素来处理数组,如果找到该元素,则返回整个数组,否则该函数返回nil或vacant。
语法:
Array_name.assoc(Object)
现在,让我们借助示例广泛地了解assoc()
函数的实现,
范例1:
=begin Ruby program to demonstrate implementation of assoc() function =end # Initializing multiple arrays of elements Arr1 = ["Fruits", "banana", "apple", "orange", "kiwi", "apricot", "Pineapple"] Arr2 = ["Languages", "C#", "Java", "Ruby", "Python", "C++","C"] Arr3 = ["Colors", "Red", "Brown", "Green", "Pink", "Yellow", "Teal"] Arr4 = ["Vegetables", "Brinjal", "Tomato", "Potato", "Reddish"] # Creating a final array of above arrays FinalArray = [Arr1, Arr2, Arr3, Arr4] # Invoking assoc() function A1 = FinalArray.assoc("Fruits") A2 = FinalArray.assoc("Languages") A3 = FinalArray.assoc("Colors") A4 = FinalArray.assoc("Vegetables") # Printing the matched contained array puts "#{A1}" puts "#{A2}" puts "#{A3}" puts "#{A4}"
输出结果
["Fruits", "banana", "apple", "orange", "kiwi", "apricot", "Pineapple"] ["Languages", "C#", "Java", "Ruby", "Python", "C++", "C"] ["Colors", "Red", "Brown", "Green", "Pink", "Yellow", "Teal"] ["Vegetables", "Brinjal", "Tomato", "Potato", "Reddish"]
代码逻辑:
在上面的示例中,我们初始化了四个数组及其类别,作为数组的第一个元素。Finalarray将这些数组存储为其元素。当使用元素作为索引调用assoc()
函数时,会将元素与每个数组的第一个元素进行比较。数组A1,A2,A3和A4正在存储包含的数组。
范例2:
=begin Ruby program to demonstrate implementation of assoc() function =end # Initializing multiple arrays of elements Arr1 = ["Fruits", "banana", "apple", "orange", "kiwi", "apricot","Pineapple"] Arr2 = ["Languages", "C#", "Java", "Ruby", "Python","C++","C"] Arr3 = ["Colors", "Red", "Brown", "Green", "Pink","Yellow","Teal"] Arr4 = ["Vegetables", "Brinjal", "Tomato", "Potato", "Raddish"] # 创建上面数组的最终数组 FinalArray = [Arr1, Arr2, Arr3, Arr4] # Taking input from user. puts "Enter the catagory:-" cat = gets.chomp arr = FinalArray.assoc(cat) if (arr==nil) puts "category not available" else puts "The available elements under the category is:-" puts "#{arr}" end
输出结果
Run 1:- Enter the category:- Colors The available elements under the category is:- ["Colors", "Red", "Brown", "Green", "Pink", "Yellow", "Teal"] Run 2:- Enter the category:- Cars category not available Run 3:- Enter the category:- Fruits The available elements under the category is:- ["Fruits", "banana", "apple", "orange", "kiwi", "apricot", "Pineapple"]
代码逻辑:
在此示例中,我们声明了四个数组,然后声明了最后一个数组。我们将类别作为用户的输入。我们正在将该类别传递给assoc()
函数。如果类别匹配,则将数组存储在包含的数组中,否则assoc()
返回nil。