问题描述:

I'm trying to get the min and max values from an array of hour strings.

So, my array is:

["09:00", "11:10", "10:00", "20:00", "15:00"]

I've tried to use gsub on all elements to remove the : and convert to int, for later use minmax function, but unsuccessful. I don't want to make some uggly code just to solve my problem.

Is there any beautiful way to do that?

网友答案:

Provided you have leading zeros:

["09:00", "11:10", "10:00", "20:00", "15:00"].minmax
  #=> ["09:00", "20:00"]
网友答案:

Another way is to convert the values and to use max_by , and convert each string in a pair of two number

["09:00", "11:10", "10:00", "20:00", "15:00"].max_by{|e| e.split(':').map(&:to_i) }

=> "20:00"
网友答案:
> a = ["09:00", "11:10", "10:00", "20:00", "15:00"]
=> ["09:00", "11:10", "10:00", "20:00", "15:00"]
> a.map(&:to_i).max
=> 20
> a.map(&:to_i).min
=> 9
相关阅读:
Top