Ruby | Array assoc() function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


Output:

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

["Names"]

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.