Reputation: 67
How can I compare the values in the array to each other in ruby?
I would like to compare the values in the array to check the maximum value of the array.
Upvotes: 1
Views: 118
Reputation: 156384
Ruby arrays (or anything that includes the Enumerable module) have a max
method:
a = [20, 30, 100, 2, 3]
a.max # => 100
If you wanted to write your own for educational purposes, you could iterate over the array while retaining the largest value seen at each point:
class Array
def my_max
max = nil # Default "max" to nil, since we haven't seen any values yet.
self.each { |x| max = x if (!x || x>max) } # Update with bigger value(s).
max # Return the max value discovered.
end
end
Or, if you are interested in functional programming consider using the Enumerable reduce
method, which generalizes the process in the my_max
version and uses the ternary operator for brevity:
class Array
def my_max2
self.reduce(nil) { |max,x| (!max || x>max) ? x : max }
end
end
Upvotes: 1
Reputation: 1509
If you are comparing integers, then
[1,3,2].max will do the work
if you are comparing integers that are stored in string format, try:
["1","3","2"].map(&:to_i).max
which will convert your string array into an int array first, and apply the max method
If you going to use such comparison often, I suggest you store the actual array in int format, so it actually saves you server some work times.
Upvotes: 1
Reputation: 5774
you can simply invoke max
a = [1,2,3,4]
a.max # outputs 4
Also for minimum value you can do
a.min # outputs 1
Upvotes: 0
Reputation: 230286
Do you want to find the maximum? It's already been done.
[1, 5, 3].max # => 5
Upvotes: 5