Ruby 数组与哈希:深入解析与应用
1. 数组排序与比较
1.1 数组排序
在 Ruby 中,数组排序可以通过 sort 方法实现。下面的代码展示了如何对包含不同类型元素的数组进行升序排序:
arr = ['h','e','l','l','o',' ',nil,'w','o','r','l','d',1,2,3,nil,4,5]
# sort ascending from nil upwards
sorted_arr = arr.sort{
|a,b|
a.to_s <=> b.to_s
}
p(sorted_arr )
这段代码会输出排序后的数组:
[nil, nil, " ", 1, 2, 3, 4, 5, "d", "e", "h", "l", "l", "l", "o", "o", "r", "w"]
若要进行降序排序,只需改变比较运算符两侧元素的顺序:
reverse_sorted_arr = arr.sort{
|a,b|
b.to_s <=> a.to_s
}
1.2 数组元素比较
比较运算符 <=> 实际上是一个方法,它定义在 Ruby 的 Comparable 模块中
超级会员免费看
订阅专栏 解锁全文
9

被折叠的 条评论
为什么被折叠?



