第一个Ruby程序

        讲到脚本语言,当下流行的无非是Ruby、Python、Perl和JSR正在讨论的Groovy,最近正在上人工智能要实现一些算法,没有规定实现语言,反正都是写,何不乘机看看脚本的魅力究竟在何处,于是我选择了在企业级应用上已经比较成熟的Ruby作为学习的第一个脚本语言,以便今后转向Ruby on Rails。
        第一个程序不是Hello world!而是汉诺塔问题,看了看Ruby的变量、数字、函数和迭代。随后如果有时间我想应该整理一下Ruby的学习笔记。

hanoi.rb源代码:
$AXIS_COUNT = 3
$DISK_COUNT = 3
def recursion_hanoi(disks, from, to)
 if disks > $DISK_COUNT || disks < 0 || from < 1 || from > $AXIS_COUNT || to < 1 || to > $AXIS_COUNT
  print "Parameters may be wrong!"
  return nil
 end
 
  if disks > 1
   tmp = getTo(from, to)
    recursion_hanoi(disks - 1, from, tmp)
    recursion_hanoi(1, from, to)
    recursion_hanoi(disks - 1, tmp, to)
  elsif disks == 1
    print "from:#{from} to:#{to} /n"
  end
end
def getTo(from, to)
 for i in 1..$AXIS_COUNT
  if(i > 0 && i!=from && i!=to)
   return i
  end
 end
end
recursion_hanoi($DISK_COUNT, 1, $AXIS_COUNT)
print "Press ENTER to return."
$stdin.gets

你可能感兴趣的:(第一个Ruby程序)