ruby学习笔记,3- 新手入门

这里是一个Ruby开发的快速参考指南:

Ruby是什么 ?

Ruby是一种纯粹的面向对象编程语言。它由日本松本幸创建于1993年。 Ruby是一种通用的解释编程语言如Perl和Python.

IRb是什么 ?

交互式Ruby(IRB)为实验提供了一个shell。内置IRB shell,你可以立即一行行查看表达式的结果。

该工具自带Ruby安装,所以你必须做一些额外的IRB工作无关。只需键入在命令提示符IRB和交互式Ruby会话将启动.

Ruby语法:

  • Ruby代码一般忽略空白字符,如空格和制表符,除非当他们出现在字符串.

  • Ruby的解释分号作为语句的结尾换行符。但是,如果ruby遇到运算符,如+, - ,或在一行的末尾的反斜杠,他们的声明中表示延续.

  • 标识符名称的变量,常量和方法。 Ruby的标识符是大小写敏感。这意味着Ram和RAM是两个不同的标识符在Ruby.

  • Ruby注释开始与pound/sharp (#)字符,去行结束(EOL).

保留字:

以下列表显示了在Ruby中的保留字。然而,这些保留字不应该被用来作为程序中的常量或变量名,被用来作为方法名称.

BEGINdonextthen
ENDelsenilltrue
aliaselsifnotundef
andendorunless
beginensureredountil
breakfalserescuewhen
caseforretrywhile
classifreturnwhile
definself__FILE__
defined?modulesuper__LINE__

Ruby定界符文本:

下面是不同的例子:

#!/usr/bin/ruby -w
print <<EOF
    This is the first way of creating
    her document ie. multiple line string.
EOF
print <<"EOF";                # same as above by www.yiibai.com
    This is the second way of creating
    her document ie. multiple line string.
EOF
print <<`EOC`                 # execute commands
        echo hi there
        echo lo there
EOC
print <<"foo", <<"bar"  # you can stack them
        I said foo.
foo
        I said bar.
bar

Ruby数据类型:

基本类型是数字,字符串,范围,数组和哈希值,.

Ruby中的整数:

123                  # Fixnum decimal
1_6889               # Fixnum decimal with underline
-5000                # Negative Fixnum
0377                 # octal
0xee                 # hexadecimal
0b1011011            # binary
?b                   # character code for 'b'
?\n                  # code for a newline (0x0a)
12345678901234567890 # Bignum

Ruby中的浮点数:

1023.4               # floating point value
1.0e6                # scientific notation
4E20                 # dot not required
4e+20                # sign before exponential

字符串常量:

Ruby字符串简单的8位字节的序列,他们是String类的对象.

  • 'VariableName': No interpolation will be done
  • "#{VariableName} and Backslashes \n:" Interpolation will be done
  • %q(VariableName): No interpolation will be done
  • %Q(VariableName and Backslashes \n): Interpolation will be done
  • %(VariableName and Backslashes \n): Interpolation will be done
  • `echo command interpretation with interpolation and backslashes`
  • %x(echo command interpretation with interpolation and backslashes)

反斜线符号:

以下是由Ruby支持反斜线符号列表:

NotationCharacter represented
\nNewline (0x0a)
\rCarriage return (0x0d)
\fFormfeed (0x0c)
\bBackspace (0x08)
\aBell (0x07)
\eEscape (0x1b)
\sSpace (0x20)
\nnnOctal notation (n being 0-7)
\xnnHexadecimal notation (n being 0-9, a-f, or A-F)
\cx, \C-xControl-x
\M-xMeta-x (c | 0x80)
\M-\C-xMeta-Control-x
\xCharacter x

Ruby数组:

创建对象引用方括号内放置一个逗号分隔的一系列Ruby数组的文字。一个被忽略尾随逗号.

例子:

#!/usr/bin/ruby
ary = [  "Ali", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
   puts i
end

这将产生以下结果:

Ali
10
3.14
This is a string
last element

Ruby 哈希:

文字的Ruby创建哈希放在括号之间的键/值对的列表,用逗号或=>之间的键和值序列。一个被忽略尾随逗号.

例子:

#!/usr/bin/ruby
hsh = colors = { "red" => 0xf00, "green" => 0x0f0 }
hsh.each do |key, value|
   print key, " is ", value, "\n"
end

这将产生以下结果:

green is 240
red is 3840

Ruby范围:

一个范围代表一个开始和结束值interval.a集。范围可使用.. E和...é文字,或使用Range.new构建.

范围使用......包含从开始运行到结束。那些使用...排除最终价值。作为一个迭代器使用时,范围返回序列中的每个值.

一个范围(1 .. 5)意味着它包括1,2,3,4,5个值和范围(1 ... 5)意味着它包括2,3,4值.

例子:

#!/usr/bin/ruby
(10..15).each do |n| 
   print n, ' ' 
end

这将产生以下结果:

10 11 12 13 14 15

变量类型:

  • $global_variable(全局变量)

  • @@class_variable(类变量)

  • @instance_variable

  • [OtherClass::]CONSTANT

  • local_variable

Ruby的伪变量:

他们是特殊的变量,局部变量的外观,但像常数。你不能指定任何这些变量的值.

  • self: The receiver object of the current method.

  • true: Value representing true.

  • false: Value representing false.

  • nil: Value representing undefined.

  • __FILE__: The name of the current source file.

  • __LINE__: The current line number in the source file.

Ruby的预定义变量:

下表列出了所有Ruby的预定义变量.

Variable NameDescription
$!The last exception object raised. The exception object can also be accessed using => in rescue clause.
$@The stack backtrace for the last exception raised. The stack backtrace information can retrieved by Exception#backtrace method of the last exception.
$/The input record separator (newline by default). gets, readline,etc., take their input record separator as optional argument.
$\The output record separator (nil by default).
$,The output separator between the arguments to print and Array#join (nil by default). You can specify separator explicitly to Array#join.
$;The default separator for split (nil by default). You can specify separator explicitly for String#split.
$.The number of the last line read from the current input file. Equivalent to ARGF.lineno.
$<Synonym for ARGF.
$>Synonym for $defout.
$0The name of the current Ruby program being executed.
$$The process pid of the current Ruby program being executed.
$?The exit status of the last process terminated.
$:Synonym for $LOAD_PATH.
$DEBUGTrue if the -d or --debug command-line option is specified.
$defoutThe destination output for print and printf ($stdout by default).
$FThe variable that receives the output from split when -a is specified. This variable is set if the -a command-line option is specified along with the -p or -n option.
$FILENAMEThe name of the file currently being read from ARGF. Equivalent to ARGF.filename.
$LOAD_PATHAn array holding the directories to be searched when loading files with the load and require methods.
$SAFEThe security level
  • 0 --> No checks are performed on externally supplied (tainted) data. (default)
  • 1 --> Potentially dangerous operations using tainted data are forbidden.
  • 2 --> Potentially dangerous operations on processes and files are forbidden.
  • 3 --> All newly created objects are considered tainted.
  • 4 --> Modification of global data is forbidden.
$stdinStandard input (STDIN by default).
$stdoutStandard output (STDOUT by default).
$stderrStandard error (STDERR by default).
$VERBOSETrue if the -v, -w, or --verbose command-line option is specified.
$- xThe value of interpreter option -x (x=0, a, d, F, i, K, l, p, v). These options are listed below
$-0The value of interpreter option -x and alias of $/.
$-aThe value of interpreter option -x and true if option -a is set. Read-only.
$-dThe value of interpreter option -x and alias of $DEBUG
$-FThe value of interpreter option -x and alias of $;.
$-iThe value of interpreter option -x and in in-place-edit mode, holds the extension, otherwise nil. Can enable or disable in-place-edit mode.
$-IThe value of interpreter option -x and alias of $:.
$-lThe value of interpreter option -x and true if option -lis set. Read-only.
$-pThe value of interpreter option -x and true if option -pis set. Read-only.
$_The local variable, last string read by gets or readline in the current scope.
$~The local variable, MatchData relating to the last match. Regex#match method returns the last match information.
$ n ($1, $2, $3...)The string matched in the nth group of the last pattern match. Equivalent to m[n], where m is a MatchData object.
$&The string matched in the last pattern match. Equivalent to m[0], where m is a MatchData object.
$`The string preceding the match in the last pattern match. Equivalent to m.pre_match, where m is a MatchData object.
$'The string following the match in the last pattern match. Equivalent to m.post_match, where m is a MatchData object.
$+The string corresponding to the last successfully matched group in the last pattern match.
$+The string corresponding to the last successfully matched group in the last pattern match.

Ruby预定义的常量:

下表列出了所有Ruby的预定义常量.

注: TRUE, FALSE 和 NIL 无是向后兼容的。这是最好用 true, false, and nil.

Constant NameDescription
TRUESynonym for true.
FALSESynonym for false.
NILSynonym for nil.
ARGFAn object providing access to virtual concatenation of files passed as command-line arguments or standard input if there are no command-line arguments. A synonym for $<.
ARGVAn array containing the command-line arguments passed to the program. A synonym for $*.
DATAAn input stream for reading the lines of code following the __END__ directive. Not defined if __END__ isn't present in code.
ENVA hash-like object containing the program's environment variables. ENV can be handled as a hash.
RUBY_PLATFORMA string indicating the platform of the Ruby interpreter.
RUBY_RELEASE_DATEA string indicating the release date of the Ruby interpreter
RUBY_VERSIONA string indicating the version of the Ruby interpreter.
STDERRStandard error output stream. Default value of $stderr.
STDINStandard input stream. Default value of $stdin.
STDOUTStandard output stream. Default value of $stdout.
TOPLEVEL_BINDINGA Binding object at Ruby's top level.

正则表达式:

语法:

/pattern/
/pattern/im    # option can be specified
%r!/usr/local! # general delimited regular expression

修饰符:

ModifierDescription
iIgnore case when matching text.
oPerform #{} interpolations only once, the first time the regexp literal is evaluated.
xIgnores whitespace and allows comments in regular expressions
mMatches multiple lines, recognizing newlines as normal characters
u,e,s,nInterpret the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding.

各种模式:

PatternDescription
^Matches beginning of line.
$Matches end of line.
.Matches any single character except newline. Using m option allows it to match newline as well.
[...]Matches any single character in brackets.
[^...]Matches any single character not in brackets
re*Matches 0 or more occurrences of preceding expression.
re+Matches 0 or 1 occurrence of preceding expression.
re{ n}Matches exactly n number of occurrences of preceding expression.
re{ n,}Matches n or more occurrences of preceding expression.
re{ n, m}Matches at least n and at most m occurrences of preceding expression.
a| bMatches either a or b.
(re)Groups regular expressions and remembers matched text.
(?imx)Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?-imx)Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?: re)Groups regular expressions without remembering matched text.
(?imx: re)Temporarily toggles on i, m, or x options within parentheses.
(?-imx: re)Temporarily toggles off i, m, or x options within parentheses.
(?#...)Comment.
(?= re)Specifies position using a pattern. Doesn't have a range.
(?! re)Specifies position using pattern negation. Doesn't have a range.
(?> re)Matches independent pattern without backtracking.
\wMatches word characters.
\WMatches nonword characters.
\sMatches whitespace. Equivalent to [\t\n\r\f].
\SMatches nonwhitespace.
\dMatches digits. Equivalent to [0-9].
\DMatches nondigits.
\AMatches beginning of string.
\ZMatches end of string. If a newline exists, it matches just before newline.
\zMatches end of string.
\GMatches point where last match finished.
\bMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\BMatches nonword boundaries.
\n, \t, etc.Matches newlines, carriage returns, tabs, etc.
\1...\9Matches nth grouped subexpression.
\10Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.

文件I/O:

常见的方法包括::

  • File.join(p1, p2, ... pN) => "p1/p2/.../pN" 独立于平台路径

  • File.new(path, modestring="r") => file

  • File.new(path, modenum [, permnum]) => file

  • File.open(fileName, aModeString="r") {|file| block} -> nil

  • File.open(fileName [, aModeNum [, aPermNum ]]) {|file| block} -> nil

  • IO.foreach(path, sepstring=$/) {|line| block}

  • IO.readlines(path) => array

这里是一个不同的模式打开一个文件列表:

ModesDescription
rRead-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
r+Read-write mode. The file pointer will be at the beginning of the file.
wWrite-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
aWrite-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

运算符和优先级:

从上到下:

:: .
[]
**
-(unary) +(unary) ! ~
*  /  %
+  -
<<  >>
&
|  ^
>  >=  <  <=
<=> == === != =~ !~
&&
||
.. ...
=(+=, -=...)
not
and or

以上都只是除了这些方法:

=, ::, ., .., ..., !, not, &&, and, ||, or, !=, !~

此外,赋值运算符(+=等)用户可定义.

控制表达式:

S.N.Control Expression
1
if bool-expr [then]
  body
elsif bool-expr [then]
  body
else
  body
end
2
unless bool-expr [then]
  body
else
  body
end
3
expr if     bool-expr
4
expr unless bool-expr
5
case target-expr
  when comparison [, comparison]... [then]
    body
  when comparison [, comparison]... [then]
    body
  ...
[else
  body]
end
6
loop do
  body
end
7
while bool-expr [do]
 body
end
8
until bool-expr [do]
 body
end
9
begin
 body
end while bool-expr
10
begin
 body
end until bool-expr
11
for name[, name]... in expr [do]
  body
end
12
expr.each do | name[, name]... |
  body
end
13
expr while bool-expr
14
expr until bool-expr
  • break 立即终止循环.
  • redo 立即重复w/w重新运行条件.
  • next 通过循环开始下一次迭代.
  • retry 重启循环,重新运行条件.

定义一个类:

类名w/ 资本开始字符.

class Identifier [< superclass ]
  expr..
end

Singleton类,一个实例添加方法

class << obj
  expr..
end

定义模块:

以下是Ruby中一般来定义一个模块的语法

module Identifier
  expr..
end

定义方法:

以下是Ruby中一般来定义一个方法的语法

def method_name(arg_list, *list_expr, &block_expr)
  expr..
end
# singleton method
def expr.identifier(arg_list, *list_expr, &block_expr)
  expr..
end
  • All items of the arg list, including parens, are optional.
  • Arguments may have default values (name=expr).
  • Method_name may be operators (see above).
  • The method definitions can not be nested.
  • Methods may override following operators:
    • .., |, ^, &, <=>, ==, ===, =~,
    • >, >=, <, <=,
    • +, -, *, /, %, **, <<, >>,
    • ~, +@, -@, [], []= (2 args)

访问限制:

  • public - 完全访问.

  • protected - 只能通过访问类和直接后裔的实例。即使是通过一个关系。 (见下文)

  • private - 只能通过类的实例访问(必须在调用nekkid没有“self”或其他).

例子:

class A
  protected
  def protected_method
    # nothing
  end
end
class B < A
  public
  def test_protected
    myA = A.new
    myA.protected_method
  end
end
b = B.new.test_protected

抛出和挽救异常:

以下是语法:

raise ExceptionClass[, "message"]
begin
  expr..
[rescue [error_type [=> var],..]
  expr..]..
[else
  expr..]
[ensure
  expr..]
end

捕捉和抛出异常:

  • catch (:label) do ... end
  • throw :label jumps back to matching catch and terminates the block.
  • + can be external to catch, but has to be reached via calling scope.
  • + Hardly ever needed.

异常类:

以下是Exception类的类层次结构:

  • Exception
    • NoMemoryError
    • ScriptError
      • LoadError
      • NotImplementedError
      • SyntaxError
    • SignalException
      • Interrupt
    • StandardError (default for rescue)
      • ArgumentError
      • IOError
        • EOFError
      • IndexError
      • LocalJumpError
      • NameError
        • NoMethodError
      • RangeError
        • FloatDomainError
      • RegexpError
      • RuntimeError (default for raise)
      • SecurityError
      • SystemCallError
        • Errno::*
      • SystemStackError
      • ThreadError
      • TypeError
      • ZeroDivisionError
    • SystemExit
    • fatal

Ruby命令行选项:

$ ruby [ options ] [.] [ programfile ] [ arguments ... ]

解释器可以调用任何下列选项来控制环境和行为的解释.

OptionDescription
-aUsed with -n or -p to split each line. Check -n and -p options.
-cChecks syntax only, without executing program.
-C dirChanges directory before executing (equivalent to -X).
-dEnables debug mode (equivalent to -debug).
-F patSpecifies pat as the default separator pattern ($;) used by split.
-e progSpecifies prog as the program from the command line. Specify multiple -e options for multiline programs.
-hDisplays an overview of command-line options.
-i [ ext]Overwrites the file contents with program output. The original file is saved with the extension ext. If ext isn't specified, the original file is deleted.
-I dirAdds dir as the directory for loading libraries.
-K [ kcode]Specifies the multibyte character set code (e or E for EUC (extended Unix code); s or S for SJIS (Shift-JIS); u or U for UTF-8; and a, A, n, or N for ASCII).
-lEnables automatic line-end processing. Chops a newline from input lines and appends a newline to output lines.
-nPlaces code within an input loop (as in while gets; ... end).
-0[ octal]Sets default record separator ($/) as an octal. Defaults to \0 if octal not specified.
-pPlaces code within an input loop. Writes $_ for each iteration.
-r libUses require to load lib as a library before executing.
-sInterprets any arguments between the program name and filename arguments fitting the pattern -xxx as a switch and defines the corresponding variable.
-T [level]Sets the level for tainting checks (1 if level not specified).
-vDisplays version and enables verbose mode
-wEnables verbose mode. If programfile not specified, reads from STDIN.
-x [dir]Strips text before #!ruby line. Changes directory to dir before executing ifdir is specified.
-X dirChanges directory before executing (equivalent to -C).
-yEnables parser debug mode.
--copyrightDisplays copyright notice.
--debugEnables debug mode (equivalent to -d).
--helpDisplays an overview of command-line options (equivalent to -h).
--versionDisplays version.
--verboseEnables verbose mode (equivalent to -v). Sets $VERBOSE to true
--yydebugEnables parser debug mode (equivalent to -y).

Ruby环境变量:

Ruby解释器使用以下环境变量来控制其行为。在env对象包含了所有当前的环境变量设置列表.

VariableDescription
DLN_LIBRARY_PATHSearch path for dynamically loaded modules.
HOMEDirectory moved to when no argument is passed to Dir::chdir. Also used by File::expand_path to expand "~".
LOGDIRDirectory moved to when no arguments are passed to Dir::chdir and environment variable HOME isn't set.
PATHSearch path for executing subprocesses and searching for Ruby programs with the -S option. Separate each path with a colon (semicolon in DOS and Windows).
RUBYLIBSearch path for libraries. Separate each path with a colon (semicolon in DOS and Windows).
RUBYLIB_PREFIXUsed to modify the RUBYLIB search path by replacing prefix of library path1 with path2 using the format path1;path2 or path1path2.
RUBYOPTCommand-line options passed to Ruby interpreter. Ignored in taint mode (Where $SAFE is greater than 0).
RUBYPATHWith -S option, search path for Ruby programs. Takes precedence over PATH. Ignored in taint mode (where $SAFE is greater than 0).
RUBYSHELLSpecifies shell for spawned processes. If not set, SHELL or COMSPEC are checked.