解释Ruby中“max”的行为

时间:2013-02-04 10:31:17

标签: ruby

我是Ruby的新手,想要了解下面这段代码。

当我有一个包含字符串的数组时,使用max函数进行操作:

names = ["aa", "bb", "cc"]
names.max = "cc" 

如果我在这里有哈希,

calendar["January", :cold, "February", :colder] 
calendar.max = ["January", :cold]

我无法理解它是最长的字大小还是显示最大索引大小的成员。谁能解释一下这种行为?我错过了一些非常基本的东西吗?

1 个答案:

答案 0 :(得分:4)

通过比较相应位置的元素来对数组进行排序。字符串按字典顺序排序。 "J""F"“更大”,因此,["January", :cold]大于["February", :colder],无论字符串长度和剩余数组元素如何。

months = %w[january february march april may june july august september october november december]

months.sort.join(', ') # => "april, august, december, february, january, july, june, march, may, november, october, september"