几个很简单的ruby脚本

下面是一个计算最大公约数的ruby脚本

#!/usr/bin/ruby
a = ARGV[0].to_i
b = ARGV[1].to_i
c = 0

while a != 0
c = b
b = a
a = c % a
end

puts b


下面是一个更简洁的写法:

#!/usr/bin/ruby
a, b = ARGV.map(&:to_i)
a, b = 0, 0 if a == 0 or b == 0
a, b = b, a % b while b != 0
puts a


下面是一个检测传入参数是否为素数的脚本

#!/usr/bin/ruby
a = ARGV[0].to_i
i = a - 1
b = 0
while i != 1
if a % i == 0
b = 1
end
i -= 1
end

if b == 0
puts "is prime."
else
puts "not prime."
end


下面是两个更简洁的写法:

#!/usr/bin/ruby
a, b = ARGV[0].to_i, 0
for i in (2..a-1)
b = i if a % i == 0
end
if b == 0
puts "is prime."
else
puts "not prime. factor is #{b}"
end



#!/usr/bin/ruby
a, b = ARGV[0].to_i, 0
2.upto(a - 1) { |i| b = i if a % i == 0 }
#(a - 2).times { |i| b = (i + 2) if a % (i + 2) == 0 }
#(2...a).each { |i| b = i if a % i == 0 }
puts b == 0 ? "is prime." : "not prime. factor is #{b}"


一个插入排序...

#!/usr/bin/ruby
array = [7, 6, 5, 1, 8, 9]

for i in (0..5)
for j in (i..5)
array[i], array[j] = array[j], array[i] while array[i] < array[j]
end
end

for i in (0..5)
print array[i], " "
end


写的更简洁的...

#!/usr/bin/ruby
array = [7,6,5,1,8,9]
6.times { |i| i.upto(5){ |j|
array[i], array[j] = array[j], array[i] while array[i] < array[j] }}
6.times { |i| print array[i], " "}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值