1

I need the index of an array in a multidimensional array if it contains a unique string.

array:

[
    {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
    {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
    {:id=>16, :name=>"Navy", :hex_value=>"285974"}
]

If hex_value of 'FFF600' exists, return the arrays position, which in this case would be 1.

This is where I am at, but it's returning [].

index = array.each_index.select{|i| array[i] == '#FFF600'}

1 Answer 1

3

That's returning nil, because there's no element i (index) in the array with value #FFF600 (nor FFF600), you need to access to the hex_value key value:

p [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
].yield_self { |this| this.each_index.select { |index| this[index][:hex_value] == 'FFF600' } }
# [1]

Giving you [1], because of using select, if you want just the first occurrence, you can use find instead.

I'm using yield_self there, to avoid assigning the array to a variable. Which is equivalent to:

array = [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
]
p array.each_index.select { |index| array[index][:hex_value] == 'FFF600' }
# [1]

Being Ruby, you can use the method for that: Enumerable#find_index

p [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
].find_index { |hash| hash[:hex_value] == 'FFF600' }
# 1
Sign up to request clarification or add additional context in comments.

1 Comment

#2 and #3 are appropriate, but I find a #1 a bit bizarre. Presumably the array has been computed or has been given as an argument to a method (not a literal), so it must already be assigned to a variable. Upvoted, but I wouldn't be displeased if you ditched #1. :-)

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.