Array的排序方法sort,用法注意点

在ruby中Array的排序方法sort用法注意点

Returns a new array created by sorting self. Comparisons for the sort will be done using the <=> operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1. See also Enumerable#sort_by.

a = [ "d", "a", "e", "c", "b" ]
a.sort #=> ["a", "b", "c", "d", "e"]
a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
以上是ruby api的说明;

我在模拟一个双色球号码生成器的case时候

def create_num
@nums = Array.new

#先选择6个红球/33球
while @nums.length < 6
@num = rand(32) + 1
unless @nums.delete(@num)
@nums << @num
end
end

#前面6个排序
@nums.sort

#后选择1个篮球/16球
@nums << rand(15) + 1
end

p create_num


我以为排序后的原数组对象会想java工具类Arrays.sort一样排一下就OK了.

public class TestCase {
final static String[] a = new String[]{"a", "g", "d", "k", "f"};
public static void main(String[] args) {
String[] b = new String[]{"a", "f", "d", "l", "c"};
Arrays.sort(b);
for(String s : b) {
System.out.println(s);
}
}
}


以上ruby代码输出是没有排序的

最后修改为



def create_num
@nums = Array.new

#先选择6个红球/33球
while @nums.length < 6
@num = rand(32) + 1
unless @nums.delete(@num)
@nums << @num
end
end

#前面6个排序
# @nums.sort
#或者用这个方法sort!
@nums.sort!
#后选择1个篮球/16球
@nums.sort << rand(15) + 1
end

p create_num


这是需要注意的一点 可能动态代码都不支持直接改变其引用吧

ps==================================
结果 gigix指点 可以用sort!方法 不太用心的原因
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值