Ruby数组比较和排序
【摘要】 笔者主要用Ruby介绍了Ruby数组比较和排序
puts(p([1,2,3]<=>[2,3,4]))#=> -1 (array 1 < array 2)
puts(p([2,3,4]<=>[1,2,3])) #=> 1 (array 1 > array 2)
puts(p([1,2,3,4]<=>[1,2,3])) #=> 1 (array 1 > array 2)all
puts(p([1,2,3,4]<=>[100,200,300])) #=> -1 (array 1 < array 2)
puts(p([1,2,3]<=>["1","2","3"])) #=> nil (invalid comparison)
-1
-1
1
1
1
1
-1
-1
nil
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
}
p(reverse_sorted_arr )
["w", "r", "o", "o", "l", "l", "l", "h", "e", "d", 5, 4, 3, 2, 1, " ", nil, nil]
class MyArray < Array
include Comparable
def <=> ( anotherArray )
self.length <=> anotherArray.length
end
end
myarr1 = MyArray.new([0,1,2,3])
myarr2 = MyArray.new([1,2,3,4])
myarr1 <=> myarr2 #=> 0
puts(p( myarr1 < myarr2 )) #=> false
puts(p( myarr1 == myarr2 )) #=> true
false
false
true
true
开发环境:Rubymine
The book of Ruby----A hands-on guide for the Adventurous---[美]Huw Collingbourne---no starch press
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区),文章链接,文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:cloudbbs@huaweicloud.com进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
- 点赞
- 收藏
- 关注作者
评论(0)