ruby中交换两个变量的值有一种简便写法:
a = 1
b = 2
a, b = b, a
puts a
# 2
puts b
# 1
经过我的测试发现这种方式的写法比自己定义个临时变量慢很多,测试代码如下(一个简单的冒泡排序算法)
arr = []
rand = Random.new
4000.times do
arr.push(rand(1000000))
end
# pop sort
def pop1(arr_t)
i = 0
arr_t.length.times do
min = arr_t[i]
(arr_t.length - i).times do |j|
if min > arr_t[i+j]
min = arr_t[i+j]
arr_t[i+j] = arr_t[i]
arr_t[i] = min
next
end
end
i += 1
end
end
def pop2(arr_t)
i = 0
arr_t.length.times do
min = arr_t[i]
(arr_t.length - i).times do |j|
if min > arr_t[i+j]
min = arr_t[i+j]
arr_t[i], arr_t[i+j] = arr_t[i+j], arr_t[i]
next
end
end
i += 1
end
end
pop1(arr)
# =》1.7s
pop2(arr)
# =》1.3s