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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With