Ruby does not support passing objects by reference, which is essentially what you are trying to do. When you call array.max
, you are passed a copy of the Fixnum
7
, and assignment and modification will be applied to this copy.
That is, you can not store a reference to this Array
element, and modify it later. You can modify the maximum value on the spot, however, using:
array[array.index(array.max)] = array.max + 10
#=> 17
array
#=> [4, 17, 1]
Note that when there are duplicate values in the Array
, array.index(array.max)
will return the index of the first one.
Storing the index for later use is not a solid solution, since, while Array
s in Ruby are ordered, the Array
or its elements can be modified between the point you retrieve the index, and the point where you decide to change the corresponding value.
Another answer suggests there's a hack to mimic pass-by-reference behaviour, but in doing this, you're working against the intention of the language, and it could lead to a lot of pain down the line.