4

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
0

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

find_index returns the item's index, the OP probably wants find
w0lf's solution will return the first match. If you want all matches, use select instead of find.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.