Just use Array#max
[5, 17, -4, 20, 12].max # => 20
If you learn and want to find it manually you can use loops.
For example
max_value = -Float::INFINITY
for item in [5, 17, -4, 20, 12] do
max_value = item if item > max_value
end
max_value # => 20
In this loop, you check all the elements of the array one by one and assign the value max_value
to the value that is currently maximal.
But in Ruby it's better to use each
for this purpose
max_value = -Float::INFINITY
[5, 17, -4, 20, 12].each { |item| max_value = item if item > max_value }
max_value # => 20
Even as an idea, for example, here's the way
[5, 17, -4, 20, 12].sort.last # => 20
As you understand it all Enumerable
and Array
methods. In Ruby it is a very powerful tool.