Ruby/Language Basics/Ruby Interpreter

Материал из

Перейти к: навигация, поиск


A Simple Ruby Program

# This file"s name is intro.rb 
puts "Hello, world!" 
numOfCoins = (10 + 20) * 2 / 3 
puts "You have #{numOfCoins} coins." 
puts "You have #{numOfCoins} coins." 
puts "You have " + numOfCoins.to_s + " coins."

Explicitly extend a statement onto the next line with a backslash

x = 10 \
    + 10

operators are actually implemented as method calls

a = 2
b = 3
c = 4
puts (a.*(b)).+(c)

Ruby Interpreter option list

Here is the syntax for the Ruby interpreter:
ruby [switches] [--] [program filename] [arguments]
Switches (or command-line options) include:
-0[ octal]       Specify record separator (\0 if no argument)
-a               Set autosplit mode with -n or -p (splits $_ into $F)
-c               Check syntax only
-C directory     cd to directory before executing your script
-d               Set debugging flags (set $DEBUG to true)
-e "command"     Execute one line of script; several -e"s allowed; omit [program filename]
-F pattern       split( ) pattern for autosplit (-a)
-i[ extension]   Edit ARGV files in place (make backup if extension is supplied)
-I directory     Specify $LOAD_PATH directory (may be used more than once)
-K kcode         Specify KANJI (Japanese) code-set
-l               Enable line-ending processing
-n               Assume "while gets( ); ... end" loop around your script
-p               Assume loop similar to -n but print line similar to sed
-r library       Require the library, before executing your script
-s               Enable some switch parsing for switches after script name
-S               Look for the script using a PATH environment variable
-T[ level]       Turn on tainting checks
-v               Print version number, then turn on verbose mode
-w               Turn on warnings for your script
-W[ level]       Set warning level: 0 for silence, 1 for medium, 2 for verbose (default)
-x[ directory]   Strip off text before #!ruby line and perhaps cd to directory
--copyright      Print the copyright
--version        Print the version (compare with -v)

Ruby is case-sensitive

numOfCoins = 6 
NumOfCoins = 10 
print "NumOfCoins: ", NumOfCoins, "\n" 
print "numOfCoins: ", numOfCoins, "\n" 
numOfCoins = numOfCoins + 1 
numOfCoins += 1 
print "After two increments, numOfCoins is ", 
numOfCoins, "\n" 
NumOfCoins = 24 
print "After reassignment, NumOfCoins is ", 
NumOfCoins, "\n"