Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable whose value is the maximum in an array

Tags:

arrays

ruby

If I have an array of variables in Ruby:

a = 4
b = 7
c = 1

array = [a, b, c]

How can I get access to the name of the variable that has the highest value? (In this example b) I want to retrieve a reference to the element with the highest value, to be able to later manipulate it:

b += 10 

I tried array.max but that just returns the max value 7

like image 480
Mushy Avatar asked Dec 25 '22 11:12

Mushy


1 Answers

When you build an array by writing array = [a, b, c], the spots in the array do not retain any kind of association with the variables named a, b, and c, so you there is no way to do exactly what you are talking about. Those variables can change without affecting the array.

You could change the way you are storing your data in order to make this possible, but without knowing what data you are storing it is hard to recommend a good way to do it. You could consider storing your data inside a hash instead of in loose variables and an array:

hash = { a: 4, b: 7, c: 1}
like image 98
David Grayson Avatar answered Jan 11 '23 09:01

David Grayson