Ruby | Array assoc() function
Last Updated :
09 Jan, 2020
The assoc() function in Ruby is used to search through an array of arrays whose first element is compared with the index of the function and return the contained array if match found otherwise return either nil or vacant.
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.
Example 1:
Array1 = [ "Alphabets" , "a" , "b" , "c" , "d" , "e" ]
Array2 = [ "Names" , "gfg" , "Geeks" , "Geek" , "GeeksforGeeks" ]
Array3 = [ "City" , "Kolkata" , "Mumbai" , "Delhi" , "Patna" ]
Array = [Array1, Array2, Array3]
A = Array .assoc( "Alphabets" )
B = Array .assoc( "City" )
C = Array .assoc( "Names" )
puts "#{A}"
puts "#{B}"
puts "#{C}"
|
Output:
["Alphabets", "a", "b", "c", "d", "e"]
["City", "Kolkata", "Mumbai", "Delhi", "Patna"]
["Names", "gfg", "Geeks", "Geek", "GeeksforGeeks"]
Example 2:
Array1 = [ "Alphabets" , "a" , "b" , "c" , "d" , "e" ]
Array2 = [ "Names" ]
Array3 = "City"
Array = [Array1, Array2, Array3]
A = Array .assoc( "Alphabets" )
B = Array .assoc( "City" )
C = Array .assoc( "Names" )
puts "#{A}"
puts "#{B}"
puts "#{C}"
|
Output:
["Alphabets", "a", "b", "c", "d", "e"]
["Names"]
Reference: https://devdocs.io/ruby~2.5/array#method-i-assoc
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...