dabadaba
dabadaba

Reputation: 9542

Ruby min function not selecting the shortest string

I don't understand why min is selecting the longest string instead of the shortest:

x='AGG'
y='AAAACTGACCCACCCCAGG'
[x,y].min #=> "AAAACTGACCCACCCCAGG" # why is this the min one?
[x,y].max #=> "AGG"

a='AGAGACTTA'
b='AAA'
[b,a].min #=> "AAA" # good
[b,a].max #=> "AGAGACTTA"

Upvotes: 2

Views: 2281

Answers (4)

Darkmouse
Darkmouse

Reputation: 1939

Ruby's min function sorts by whether a string is greater than another one. In this case String Y occurs earlier in the alphabet than string X, therefore it's less than string X. If you want to find which is the shortest string you could do something like.

[x,y].min_by(&:length)
=> "AGG"

To find the longest string you would do

[x,y].max_by(&:length)

Upvotes: 1

SlySherZ
SlySherZ

Reputation: 1661

The problem is that min/max doesn't do what you think it does. It doesn't compare string sizes, just gives you the first one in alphabetic order. Luckily, min / max functions allow you to define how to check which object is bigger. Try something like:

arr.min {|a,b| a.length <=> b.length}
arr.max {|a,b| a.length <=> b.length}

Upvotes: 0

Esse
Esse

Reputation: 3298

Normally Ruby uses something called lexicographical ordering to get minimum and maximum string. Therefore AGG > AAAACTGACCCACCCCAGG, because G > A (first letter they differ in).

To get your expected behaviour you need to manually provided comparator block, like this:

[x,y].min { |x,y| x.size <=> y.size }

Upvotes: 2

Amadan
Amadan

Reputation: 198506

Because it is not comparing by string length, but by lexicographical ordering; and AA comes before AG. If you want to compare by length, you need to specify it:

p [x,y].min_by(&:length)

Upvotes: 1

Related Questions