views:

43

answers:

1

Background: In Ruby I have a 2d array like the following:

count[[english_word, french_word]] = ...
pp count
{["my", "une"]=>0.0,
 ["my", "voiture"]=>0.2,
 ["red", "maison"]=>0.9,
...
}

(The reason I did this rather than count[english_word][french_word] was I wasn't sure how to get around the Undef errors, and I saw this syntax suggested on Stack Overflow)

I've filled the data structure with a pair of nested loops using a english_vocab and french_vocab arrays of all words.

Question: I would like to be able to get the maximum of a given English word.

english_word = 'foo'
max_count = 0
french_vocab.each do |french_word|
   count = count[[english_word, french_word]]
   if count > max_count
       max_count = count
   end
end

I can do this with a simple nested for loop, but I'm wondering if there's a nicer Ruby-ish way of doing the same thing?

+2  A: 

I think it's much easier than you're thinking it is.

hash = {
  ["my", "une"]=>0.0,
  ["my", "voiture"]=>0.2,
  ["red", "maison"]=>0.9,
}

puts hash.find_all{|a| a[0][0] == 'my' }.max[1]
AboutRuby
This works really well. Thanks!
Ben Humphreys