2

Trying to look through an array and see if a particular value is set and if it is, update the numbers attached to it.

Example:

test = [['test',1,2],['watch',1,2],['fish',1,2]]

So I'd like to search this array for 'test' - if it exists, amend the values '1,2', if it doesn't exist, just add the new search term into the array.

New to ruby and having trouble searching inside a multi-dimensional array and getting the key back

4
  • Why do you use Array not Hash? Commented Oct 3, 2011 at 12:27
  • Like I said, Im new to Ruby - as I understand it a Hash would just form an associative array instead of a numerical one? I'm not seeing how that would help me search inside the multi-dimensional array. It's not a key=>value relationship, there's 3 terms inside each subarray Commented Oct 3, 2011 at 12:30
  • 2
    mmm and if you use sth like test = [ :test=>[1,2], :watch => [1,2], :fish => [1,2] ] Commented Oct 3, 2011 at 12:36
  • Aye just realised that as I went for a quick walk round the block. Will give it a whirl, thanks for putting me onto this tack Commented Oct 3, 2011 at 12:51

1 Answer 1

2

I'd go for the hash method suggested in the comments, but if you're really wanting to store your data in the multidimensional array like that I suppose you could do something like:

search_term = "test"
search_item= nil
test.each do |item|
  if item.include? search_term
    search_item = item
  end
end

if search_item.nil?
  test << [search_term]
else
  search_item << [1,2]
end

I think that would do it (although I'm a little fuzzy on what you were wanting to do after you found the item).

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

1 Comment

I did indeed go with the Hash method in the end. This method does look workable as well though and is technically the answer to the initial question

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.