在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时候
我以为排序后的原数组对象会想java工具类Arrays.sort一样排一下就OK了.
以上ruby代码输出是没有排序的
最后修改为
这是需要注意的一点 可能动态代码都不支持直接改变其引用吧
ps==================================
结果 gigix指点 可以用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!方法 不太用心的原因