简体   繁体   中英

Ruby Array and .max

I'm very confused here.

Why does ["4", "5", "29", "54", "4", "0", "-214", "542", "-64", "1", "-3", "6", "-6"].max

return 6 and not 542

After deleting 6 from the array, then it returns 542

using .min works correctly as well.

/mind-boggled

For reference, I've been using the Ruby IDEs from CodeWars, tutorialspoint.com and labs.codecademy.com/

Because this is a string array, you should convert elements to numbers.

["4", "5", "29", "54", "4", "0", "-214", "542", "-64", "1", "-3", "6", "-6"].map(&:to_i).max
=> 542

ruby compare words characters by ASCLL value.

"6" > "542"
=> true

You can get ASCll value of character by each_byte :

"0123456789".each_byte { |e| puts e }    
49
50
51
52
53
54
55
56
57

It is an array of strings, so it's treated as if it's alphabetical versus numeric. That means that just like "za" would come after "azzzzzzz" , "6" comes after (is more than) "5" . Similarly, "51" would come after "5" in the same way "ab" would come after "a" and so on.

Strings are compared with Lexicographical order .

You can use Enumerable#max_by to specify how to compare them:

["4", "5", "29", "54", "4", "0", "-214", "542", "-64", "1", "-3", "6", "-6"].max_by(&:to_i)
#=> "542"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM