tags:

views:

311

answers:

2

This is what I have so far

ages   = [20,19,21,17,31,33,34]
names  = [Bob, Bill, Jill, Aimee, Joe, Matt, Chris]

How do I take ages and apply a method to it to extract the largest integer out of it and learn its indexed position. The reason being I want to know which person in names is the oldest. Parallel assignment is blocking my ability to do a .sort on the array becasue it changes the position of element associted with names.

Please include code to mull over thanks,

+1  A: 
names[ages.index(ages.max)]

What it does is find the maximum value in ages (ages.max), get the index of the first matching value in ages, and use it to get the corresponding person. Note that if two or more people have the same age which is the maximum, it'll only give you the name of the first one in the array.

Edit: To address your comment, I'm not sure why you need this parallel arrays structure (it'd be much easier if you just had a person object). Nevertheless, you can try something like:

indices = []
ages.each_with_index { |age, i| indices << i if age < 20 }
indices.each { |i| puts names[i] }
Firas Assaad
Hmmm trying to determine value other then min or max like 20 still leaves me in the dark after about an hour of trying different stuff. Heres what I am trying to do. Find all age values less then 20. Takes its indexed element position and return the name for value below 20 ages = [20,19,21,17,31,33,34] names = [Bob, Bill, Jill, Aimee, Joe, Matt, Chris]So I think it should be: puts names[ages.each_index {|n| n<20 }]I'm returning something wrong inside names though. Obviously the output should be Bob, Bill, Aimee. THanks for the help on parallel arrays,Matt
Matt
Hmm.. the problem with that code is that by using each_index you are comparing indices with 20, and doing nothing with it (each_index just executes the block passing it each index, but your block evaluates to true or false without side effects). Furthermore, each_index returns the array, and you can't use an array as index for another array. I've updated my answer with code that should do what you want (prints Bill and Aimee only, because Bob is 20, and 20 is not less than 20).
Firas Assaad
+6  A: 
ages.zip(names).max
jrhicks