Simple examples

上一篇 / 下一篇  2010-10-17 21:17:25 / 个人分类:Ruby

Let's write a function to compute factorials. The mathematical definition of n factorial
is:
n! = 1                (when n==0)
   = n * (n-1)!       (otherwise)

Run in SciTE editor

def fact(n)
  if n == 0
    1
  else
    n * fact(n-1)
  end
end

puts fact(5)


Run in command line CMD
see attachment


#Program to find the factorial of number
# Save this as fact.rb
def fact(n)
 if n==0
  1
 else
  n*fact(n-1)
 end
end
puts fact(ARGV[0].to_i)
#Here, ARGV is an array which contains the command line arguments, and to_i converts a character string to an integer.

When you invoke ruby with no arguments,it reads commands from standard input and
executes then after the end of input:
ruby
puts "hello world"
puts "good-bye world"
^D

The ^D above means control-D, a conventional way to signal end-of-input in a Unix context.

ruby
puts "hello world"
puts "good-bye world"
^Z

In DOS/Windows, try pressing F6 or ^Z instead.


TAG:

 

评分:0

我来说两句

Open Toolbar