ruby - 可数的例子 - 困惑

时间:2015-08-21 11:03:38

标签: ruby

我是红宝石的新手。我对可枚举的例子感到困惑。

a = %w(albatross dog horse)  
a.max    #Answer: "horse"   --why horse?
a.max(2) #Answer: ["horse", "dog"] --why horse,dog?

请解释。

4 个答案:

答案 0 :(得分:4)

按字母顺序排列:

  1. lbatross
  2. d OG
  3. ħ ORSE
  4. max按降序返回这些值(即以最大值开头):

    a.max    #=> "horse"
    a.max(1) #=> ["horse"]
    a.max(2) #=> ["horse", "dog"]
    a.max(3) #=> ["horse", "dog", "albatross"]
    

    min执行相反的操作(即以最小值开头):

    a.min    #=> "albatross"
    a.min(1) #=> ["albatross"]
    a.min(2) #=> ["albatross", "dog"]
    a.min(3) #=> ["albatross", "dog", "horse"]
    

答案 1 :(得分:2)

因为h位于d之后,后面是a的ASCII代码。

答案 2 :(得分:0)

这就是原因:

"a" > "b" #=> false

"a" < "b" # => true

ASCII中具有较高值(因此字母表)的字符在Ruby中具有较高的值。将n传递给max方法,您将获得具有最高值的数组的n元素。

答案 3 :(得分:0)

这是因为enumerable的max方法使用<=>运算符来比较对象,comparable mixin用它来比较对象,在你的情况下,你有一个Enumerable字符串和字符串包括comparable,因此重写<=>运算符,这是字母顺序,请参阅:

puts 'albatross' <=> 'horse' # -1 
puts 'albatross' <=> 'dog' # -1
puts 'horse' <=> 'dog' # 1

如果第一个字符串按字母顺序排在第二个字符串之前,则方法返回-1,否则方法返回1(如果字符串等于,则返回0)。

希望有所帮助