Rubyist Rubyist - 4 months ago 9
Ruby Question

Largest one among specific strings having multiple dots

I am trying to find the larger value between two decimal values or integers in specific format. For example,


  • compare
    2.2
    with
    2.1.5
    .
    2.2
    is the larger

  • compare
    2.3.3
    with
    2.3.456
    .
    2.3.456
    is the larger.



I cannot process it. Please suggest something to resolve this.

Answer

You can create an array from each version:

def to_version(s)
  s.split('.').map(&:to_i)
end

to_version('2.3.3')
# => [2, 3, 3]

Now you can compare the two results (arrays are comparable):

['2.2', '2.1.5'].max_by { |x| to_version(x) }
# => "2.2"
['2.3.3', '2.3.456'].max_by { |x| to_version(x) }
# => "2.3.456"
['2.13.3', '2.3.456'].max_by { |x| to_version(x) }
# => "2.13.3"
Comments