Max method
For numeric data, Max gets the maximum value of the array, and Min gets the minimum value of the array.
There is no real meaning to the size of the string array comparison,
The example given in Ruby is
# Enum.max -> obj
# enum.max {|a, b| block}-> obj
#a =%w (Albatross dog)
#a. Max Horse "Horse"
# A.max {|a, b| a.length <=> b.length} #=> "Albatross"
Experiments in practice
D=%w (Albatross Dog Horse ddd Dasgfds)
d.max => "Horse"
It's weird, what's going on?
Print a more intuitive numeric string for this
A = ["1", "3", "I", "777", "2", "4", "6", "8", "0"]
def Max (first,*rest)
max=first
Rest.each do |x|
P "---#{x}---#{max}"
max=x if X>max
p "---#{x}---#{max}"
Max
End
Run
Copy Code code as follows:
Result is
"---3---1"
"---3---3"---777---3 "------777---" "---
777
---" "--- 2---777 "
"---2---777 "
"---4---777 "
"---4---777 "
"---6---777 ""---6
---777 "
"---8- --777 "
"---8---8 "
"---0---8 "
"---0---8 "
=>" 8 "
The problem comes out, "8" > "777" => true, and then test
"7" > "777" => false
"6" > "777" => false
"9" > "777" => true
"ten" > "777" => False
"One" > "777" => false
">" 777 "=> false" "
>" 777 "=> true
The crash, the law is not friendly, because the use of the size of Max This method, previously thought he was the size of the ASCII encoding, see today about sort sorting problems found this problem, here is a dictionary sort of method to take the maximum value.
Here's a look at the sort in Ruby:
Sort Sorting method
Ary.sort -> new_ary
ary.sort {|a, b| block}-> new_ary enum.sort_by
{|obj| block} -> Arra Y
enum.sort_by -> an_enumerator
Instance
h=[' 1 ', ' 3 ', ' ', ', ' 7 ', '
A. P h.sort
B. P h.sort{|a,b| a.to_i <=> b.to_i}
C. P h.sort_by{|x| x.to_ I
The output is as follows:
A. ["1", "Ten", "", "3", "7"]
B. ["1", "3", "7", "Ten", "a"]
C. ["1", "3", "7", "10", "13"]
1. In the absence of a specified block, sort defaults are sorted in the order of the dictionaries.
2. If a block is specified, sorting the values is sorted by the size of the value of the block-making method.
The 3.sort_by method is sorted by the results generated by the code of the execution block, which executes only one block of calls per element, which is faster than B.