Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching array of objects for item in Ruby

I am trying to search through an array of objects for a value, but am having trouble getting the find_index to work. In my code below, I am trying to search for the name (joseph) in the array. Is this the best way? I want to return that object after I search and find it.

name = "joseph"

array = [{"login":"joseph","id":4,"url":"localhost/joe","description":null},
{"login":"billy","id":10,"url":"localhost/billy","description":null}]

arrayItem = array.find_index {|item| item.login == name}

puts arrayItem
like image 922
user2816352 Avatar asked Jan 08 '23 15:01

user2816352


1 Answers

Your array contains a Hash, with keys that are symbols (in hashes, key: value is a shorthand for :key => value). Therefore, you need to replace item.login with item[:login]:

name = "joseph"

array = [{"login":"joseph","id":4,"url":"localhost/joe","description":nil},
{"login":"billy","id":10,"url":"localhost/billy","description":nil}]

arrayIndex = array.find_index{ |item| item[:login] == name }

puts arrayIndex

The code above retrieves the index at which the sought object is in the array. If you want the object and not the index, use find instead of find_index:

arrayItem = array.find{ |item| item[:login] == name }

Also, note that in Ruby, null is actually called nil.

like image 82
Cristian Lupascu Avatar answered Jan 10 '23 05:01

Cristian Lupascu