ITeye博客

几个很简单的ruby脚本

polyahu · 2013-02-14 22:08 · ruby · 编程语言 · Markdown

下面是一个计算最大公约数的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], " "}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。