Advertisement
Guest User

Untitled

a guest
Sep 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.49 KB | None | 0 0
  1. Lexical structure
  2.  
  3. The character set used in the Ruby source files for the current implementation is based on ASCII. The case of characters in source files is significant. All syntactic constructs except identifiers and certain literals may be separated by an arbitrary number of whitespace characters and comments. The whitespace characters are space, tab, vertical tab, backspace, carriage return, and form feed. Newlines works as whitespace only when expressions obviously continues to the next line.
  4.  
  5. Identifiers
  6.  
  7. Examples:
  8.  
  9. foobar
  10. ruby_is_simple
  11. Ruby identifiers are consist of alphabets, decimal digits, and the underscore character, and begin with a alphabets(including underscore). There are no restrictions on the lengths of Ruby identifiers.
  12.  
  13. Comment
  14.  
  15. Examples:
  16.  
  17. # this is a comment line
  18. Ruby comments start with "#" outside of a string or character literal (?#) and all following text until the end of the line.
  19.  
  20. Embedded Documentation
  21.  
  22. Example:
  23.  
  24. =begin
  25. the everything between a line beginning with `=begin' and
  26. that with `=end' will be skipped by the interpreter.
  27. =end
  28. If the Ruby interpreter encounters a line beginning with =begin, it skips that line and all remaining lines through and including a line that begins with =end.
  29.  
  30. Reserved words
  31.  
  32. The reserved words are:
  33.  
  34. BEGIN class ensure nil self when
  35. END def false not super while
  36. alias defined for or then yield
  37. and do if redo true
  38. begin else in rescue undef
  39. break elsif module retry unless
  40. case end next return until
  41. Program
  42.  
  43. Example:
  44.  
  45. print "hello world!\n"
  46. Ruby programs are sequence of expressions. Each expression are delimited by semicolons(;) or newlines. Backslashes at the end of line does not terminate expression.
  47.  
  48. Expression
  49.  
  50. Examples:
  51.  
  52. true
  53. (1+2)*3
  54. foo()
  55. if test then ok else ng end
  56. Ruby expressions can be grouped by parentheses.
  57.  
  58. String literals
  59.  
  60. Examples:
  61.  
  62. "this is a string expression\n"
  63. "concat#{foobar}"
  64. 'concat#{foobar}'
  65. %q!I said, "You said, 'She said it.'"!
  66. %!I said, "You said, 'She said it.'"!
  67. %Q('This is it.'\n)
  68. String expressions begin and end with double or single quote marks. Double-quoted string expressions are subject to backslash escape and expression substitution. Single-quoted strings are not (except for \' and \\).
  69.  
  70. The string expressions begin with % are the special form to avoid putting too many backslashes into quoted strings. The %q/STRING/ expression is the generalized single quote. The %Q/STRING/ (or %/STRING/) expression is the generalized double quote. Any non-alphanumeric delimiter can be used in place of /, including newline. If the delimiter is an opening bracket or parenthesis, the final delimiter will be the corresponding closing bracket or parenthesis. (Embedded occurrences of the closing bracket need to be backslashed as usual.)
  71.  
  72. Backslash notation
  73.  
  74. \t
  75. tab(0x09)
  76. \n
  77. newline(0x0a)
  78. \r
  79. carriage return(0x0d)
  80. \f
  81. form feed(0x0c)
  82. \b
  83. backspace(0x08)
  84. \a
  85. bell(0x07)
  86. \e
  87. escape(0x1b)
  88. \s
  89. whitespace(0x20)
  90. \nnn
  91. character in octal value nnn
  92. \xnn
  93. character in hexadecimal value nn
  94. \cx
  95. control x
  96. \C-x
  97. control x
  98. \M-x
  99. meta x (c | 0x80)
  100. \M-\C-x
  101. meta control x
  102. \x
  103. character x itself
  104. The string literal expression yields new string object each time it evaluated.
  105.  
  106. Command output
  107.  
  108. Examples:
  109.  
  110. `date`
  111. %x{ date }
  112. Strings delimited by backquotes are performed by a subshell after escape sequences interpretation and expression substitution. The standard output from the commands are taken as the value. Commands performed each time they evaluated.
  113.  
  114. The %x/STRING/ is the another form of the command output expression.
  115.  
  116. Regular expression
  117.  
  118. Examples:
  119.  
  120. /^Ruby the OOPL/
  121. /Ruby/i
  122. /my name is #{myname}/o
  123. %r|^/usr/local/.*|
  124. Strings delimited by slashes are regular expressions. The characters right after latter slash denotes the option to the regular expression. Option i means that regular expression is case insensitive. Option i means that regular expression does expression substitution only once at the first time it evaluated. Option x means extended regular expression, which means whitespaces and commens are allowd in the expression. Option p denotes POSIX mode, in which newlines are treated as normal character (matches with dots).
  125.  
  126. The %r/STRING/ is the another form of the regular expression.
  127.  
  128. ^
  129. beginning of a line or string
  130. $
  131. end of a line or string
  132. .
  133. any character except newline
  134. \w
  135. word character[0-9A-Za-z_]
  136. \W
  137. non-word character
  138. \s
  139. whitespace character[ \t\n\r\f]
  140. \S
  141. non-whitespace character
  142. \d
  143. digit, same as[0-9]
  144. \D
  145. non-digit
  146. \A
  147. beginning of a string
  148. \Z
  149. end of a string, or before newline at the end
  150. \z
  151. end of a string
  152. \b
  153. word boundary(outside[]only)
  154. \B
  155. non-word boundary
  156. \b
  157. backspace(0x08)(inside[]only)
  158. [ ]
  159. any single character of set
  160. *
  161. 0 or more previous regular expression
  162. *?
  163. 0 or more previous regular expression(non greedy)
  164. +
  165. 1 or more previous regular expression
  166. +?
  167. 1 or more previous regular expression(non greedy)
  168. {m,n}
  169. at least m but most n previous regular expression
  170. {m,n}?
  171. at least m but most n previous regular expression(non greedy)
  172. ?
  173. 0 or 1 previous regular expression
  174. |
  175. alternation
  176. ( )
  177. grouping regular expressions
  178. (?# )
  179. comment
  180. (?: )
  181. grouping without backreferences
  182. (?= )
  183. zero-width positive look-ahead assertion
  184. (?! )
  185. zero-width negative look-ahead assertion
  186. (?ix-ix)
  187. turns on (or off) `i' and `x' options within regular expression. These modifiers are localized inside an enclosing group (if any).
  188. (?ix-ix: )
  189. turns on (or off) `i' and `x' options within this non-capturing group.
  190. Backslash notation and expression substitution available in regular expressions.
  191.  
  192. Expression substitution in strings
  193.  
  194. Examples:
  195.  
  196. "my name is #{$ruby}"
  197. In double-quoted strings, regular expressions, and command output expressions, the form like "#{expression}" extended to the evaluated result of that expression. If the expressions are the variables which names begin with the character either `$',`@', expressions are not needed to be surrounded by braces. The character `#' is interpreted literally if it it not followed by characters `{',`$',`@'.
  198.  
  199. line-oriented string literals (Here document)
  200.  
  201. There's a line-oriente form of the string literals that is usually called as `here document'. Following a << you can specify a string or an identifier to terminate the string literal, and all lines following the current line up to the terminator are the value of the string. If the terminator is quoted, the type of quotes determines the type of the line-oriented string literal. Notice there must be no space between << and the terminator.
  202.  
  203. If the - placed before the delimiter, then all leading whitespcae characters (tabs or spaces) are stripped from input lines and the line containing delimiter. This allows here-documents within scripts to be indented in a natural fashion.
  204.  
  205. print <<EOF
  206. The price is #{$Price}.
  207. EOF
  208.  
  209. print <<"EOF"; # same as above
  210. The price is #{$Price}.
  211. EOF
  212.  
  213. print <<`EOC` # execute commands
  214. echo hi there
  215. echo lo there
  216. EOC
  217.  
  218. print <<"foo", <<"bar" # you can stack them
  219. I said foo.
  220. foo
  221. I said bar.
  222. bar
  223.  
  224. myfunc(<<"THIS", 23, <<'THAT')
  225. Here's a line
  226. or two.
  227. THIS
  228. and here's another.
  229. THAT
  230.  
  231. if need_define_foo
  232. eval <<-EOS # delimiters can be indented
  233. def foo
  234. print "foo\n"
  235. end
  236. EOS
  237. end
  238.  
  239. Numeric literals
  240.  
  241. 123
  242. integer
  243. -123
  244. integer(signed)
  245. 1_234
  246. integer(underscore within decimal numbers ignored)
  247. 123.45
  248. floating point number
  249. 1.2e-3
  250. floating point number
  251. 0xffff
  252. hexadecimal integer
  253. 0b01011
  254. binary integer
  255. 0377
  256. octal integer
  257. ?a
  258. ASCII code for character `a'(97)
  259. ?\C-a
  260. Control-a(1)
  261. ?\M-a
  262. Meta-a(225)
  263. ?\M-\C-a
  264. Meta-Control-a(129)
  265. :symbol
  266. Integer corresponding identifiers, variable names, and operators.
  267. In ?-representation all backslash notations are available.
  268.  
  269. Variables and constants
  270.  
  271. The variable in Ruby programs can be distinguished by the first character of its name. They are either global variables, instance variables, local variables, and class constants. There are no restriction for variable name length (except heap size).
  272.  
  273. Global variables
  274.  
  275. Examples:
  276.  
  277. $foobar
  278. $/
  279. The variable which name begins with the character `$', has global scope, and can be accessed from any location of the program. Global variables are available as long as the program lives. Non-initialized global variables has value nil.
  280.  
  281. Instance variables
  282.  
  283. Examples:
  284.  
  285. @foobar
  286. The variable which name begins which the character `@', is an instance variable of self. Instance variables are belong to the certain object. Non-initialized instance variables has value nil.
  287.  
  288. Constants
  289.  
  290. Examples:
  291.  
  292. FOOBAR
  293. The identifier which name begins with upper case letters ([A-Z]) is an constant. The constant definitions are done by assignment in the class definition body. Assignment to the constants must be done once. Changing the constant value or accessing to the non-initialized constants raises a NameError exception.
  294.  
  295. The constants can be accessed from:
  296.  
  297. the class or module body in which the constant is defined, including the method body and the nested module/class definition body.
  298. the class which inherit the constant defining class.
  299. the class or module which includes the constant defining module.
  300. Class definition defines the constant automatically, all class names are constants.
  301.  
  302. To access constants defined in certain class/module, operator :: can be used.
  303.  
  304. To access constants defined in the Object class, operator :: without the left hand side operand can be used.
  305.  
  306. Examples:
  307.  
  308. Foo::Bar
  309. ::Bar
  310. No assignment using operator `::' is permitted.
  311.  
  312. Local variables
  313.  
  314. Examples:
  315.  
  316. foobar
  317. The identifier which name begins with lower case character or underscore, is a local variable or a method invocation. The first assignment in the local scope (bodies of class, module, method definition) to such identifiers are declarations of the local variables. Non-declared identifiers are method invocation without arguments.
  318.  
  319. The local variables assigned first time in the blocks are only valid in that block. They are called `dynamic variables.' For example:
  320.  
  321. i0 = 1
  322. loop {
  323. i1 = 2
  324. print defined?(i0), "\n" # true
  325. print defined?(i1), "\n" # true
  326. break
  327. }
  328. print defined?(i0), "\n" # true
  329. print defined?(i1), "\n" # false
  330. Pseudo variables
  331.  
  332. There are special variables called `pseudo variables'.
  333.  
  334. self
  335. the receiver of the current method
  336. nil
  337. the sole instance of the Class NilClass(represents false)
  338. true
  339. the sole instance of the Class TrueClass(typical true value)
  340. false
  341. the sole instance of the Class FalseClass(represents false)
  342. __FILE__
  343. the current source file name.
  344. __LINE__
  345. the current line number in the source file.
  346. The values of the pseudo variables cannot be changed. Assignment to these variables causes exceptions.
  347.  
  348. Array expression
  349.  
  350. Examples:
  351.  
  352. [1, 2, 3]
  353. Syntax:
  354.  
  355. `[' expr,...`]'
  356. Returns an array, which contains result of each expressions. Arrays are instances of the class Array.
  357.  
  358. %w expressions make creation of the arrays of strings easier. They are equivalent to the single quoted strings split by the whitespaces. For example:
  359.  
  360. %w(foo bar baz)
  361. is equivalent to ["foo", "bar", "baz"]. Note that parenthesis right after %s is the quote delimiter, not usual parenthesis.
  362.  
  363. Hash expression
  364.  
  365. Examples:
  366.  
  367. {1=>2, 2=>4, 3=>6}
  368. Syntax:
  369.  
  370. { expr => expr...}
  371. Returns a new Hash object, which maps each key to corresponding value. Hashes are instances of the class Hash.
  372.  
  373. Method invocation
  374.  
  375. Examples:
  376.  
  377. foo.bar()
  378. foo.bar
  379. bar()
  380. print "hello world\n"
  381. print
  382. Syntax:
  383.  
  384. [expr `.'] identifier [`(' expr...[`*' [expr]],[`&' ] expr`)']
  385. [expr `::'] identifier [`(' expr...[`*' [expr]],[`&' expr] `)']
  386. Method invocation expression invokes the method of the receiver (right hand side expression of the dot) specified by the identifier. If no receiver specified, self is used as a receiver.
  387.  
  388. Identifier names are normal identifiers and identifier suffixed by character ? or !. As a convention, identifier? are used as predicate names, and identifier! are used for the more destructive (or more dangerous) methods than the method which have same name without !.
  389.  
  390. If the last argument expression preceded by *, the value of the expression expanded to arguments, that means
  391.  
  392. foo(*[1,2,3])
  393. equals
  394. foo(1,2,3)
  395. If the last argument expression preceded by &, the value of the expression, which must be a Proc object, is set as the block for the calling method.
  396.  
  397. Some methods are private, and can be called from function form invocations (the forms that omits receiver).
  398.  
  399. super
  400.  
  401. Examples:
  402.  
  403. super
  404. super(1,2,3)
  405. Syntax:
  406.  
  407. super
  408. super(expr,...)
  409. the super invokes the method which the current method overrides. If no arguments given, arguments to the current method passed to the method.
  410.  
  411. Assignment
  412.  
  413. Examples:
  414.  
  415. foo = bar
  416. foo[0] = bar
  417. foo.bar = baz
  418. Syntax:
  419.  
  420. variable '=' expr
  421. constant '=' expr
  422. expr`['expr..`]' '=' expr
  423. expr`.'identifier '=' expr
  424. Assignment expression are used to assign objects to the variables or such. Assignments sometimes work as declarations for local variables or class constants. The left hand side of the assignment expressions can be either:
  425.  
  426. variables
  427. variables `=' expression
  428. If the left hand side is a variables, then assignment is directly performed.
  429.  
  430. array reference
  431. expr1`[' expr2...`]' `=' exprN
  432. This from is evaluated to the invocation of the method named []=, with expr1 as the receiver, and values expr2 to exprN as arguments.
  433.  
  434. attribute reference
  435. expr `.' identifier `=' expr
  436. This from is evaluated to the invocation of the method named identifier= with the right hand side expression as a argument.
  437.  
  438. self assignment
  439.  
  440. Examples:
  441.  
  442. foo += 12
  443. Syntax:
  444.  
  445. expr op= expr # left hand side must be assignable.
  446. This form evaluated as expr = expr op expr. But right hand side expression evaluated once. op can be one of:
  447.  
  448. +, -, *, /, %, **, &, |, ^, <<, >>, &&, ||
  449. There may be no space between operators and =.
  450.  
  451. Multiple assignment
  452.  
  453. Examples:
  454.  
  455. foo, bar, baz = 1, 2, 3
  456. foo, = list()
  457. foo, *rest = list2()
  458. Syntax:
  459.  
  460. expr `,' [expr `,'...] [`*' expr] = expr [, expr...][`*' [expr]]
  461. `*' expr = expr [, expr...][`*' expr]
  462. Multiple assignment form performs multiple assignment from expressions or an array. Each left hand side expression must be assignable. If single right hand side expression given, the value of the expression converted into an array, then each element in array assigned one by one to the left hand side expressions. If number of elements in the array is greater than left hand sides, they are just ignored. If left hand sides are longer than the array, nil will be added to the locations.
  463.  
  464. Multiple assignment acts like this:
  465.  
  466. foo, bar = [1, 2] # foo = 1; bar = 2
  467. foo, bar = 1, 2 # foo = 1; bar = 2
  468. foo, bar = 1 # foo = 1; bar = nil
  469.  
  470. foo, bar, baz = 1, 2 # foo = 1; bar = 2; baz = nil
  471. foo, bar = 1, 2, 3 # foo = 1; bar = 2
  472. foo,*bar = 1, 2, 3 # foo = 1; bar = [2, 3]
  473. The value of the multiple assignment expressions are the array used to assign.
  474.  
  475. Operator expressions
  476.  
  477. Examples:
  478.  
  479. 1+2*3/4
  480. As a syntax sugar, several methods and control structures has operator form. Ruby has operators show below:
  481.  
  482. high ::
  483. []
  484. **
  485. -(unary) +(unary) ! ~
  486. * / %
  487. + -
  488. << >>
  489. &
  490. | ^
  491. > >= < <=
  492. <=> == === != =~ !~
  493. &&
  494. ||
  495. .. ...
  496. =(+=, -=...)
  497. not
  498. low and or
  499. Most of operators are just method invocation in special form. But some operators are not methods, but built in to the syntax:
  500.  
  501. =, .., ..., !, not, &&, and, ||, or, !=, !~
  502. In addition, assignment operators(+= etc.) are not user-definable.
  503.  
  504. Control structure
  505.  
  506. Control structures in Ruby are expressions, and have some value. Ruby has the loop abstraction feature called iterators. Iterators are user-definable loop structure.
  507.  
  508. if
  509.  
  510. Examples:
  511.  
  512. if age >= 12 then
  513. print "adult fee\n"
  514. else
  515. print "child fee\n"
  516. end
  517. gender = if foo.gender == "male" then "male" else "female" end
  518. Syntax:
  519.  
  520. if expr [then]
  521. expr...
  522. [elsif expr [then]
  523. expr...]...
  524. [else
  525. expr...]
  526. end
  527. if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif.
  528.  
  529. If conditional part of if is the regular expression literal, then it evaluated like:
  530.  
  531. $_ =~ /re/
  532. if modifier
  533.  
  534. Examples:
  535.  
  536. print "debug\n" if $debug
  537. Syntax:
  538.  
  539. expr if expr
  540. executes left hand side expression, if right hand side expression is true.
  541.  
  542. unless
  543.  
  544. Examples:
  545.  
  546. unless $baby
  547. feed_meat
  548. else
  549. feed_milk
  550. end
  551. Syntax:
  552.  
  553. unless expr [then]
  554. expr...
  555. [else
  556. expr...]
  557. end
  558. unless expressions are used for reverse conditional execution. It is equivalent to:
  559.  
  560. if !(cond)
  561. ...
  562. else
  563. ...
  564. end
  565. unless modifier
  566.  
  567. Examples:
  568.  
  569. print "stop\n" unless valid($passwd)
  570. Syntax:
  571.  
  572. expr unless expr
  573. executes left hand side expression, if right hand side expression is false.
  574.  
  575. case
  576.  
  577. Examples:
  578.  
  579. case $age
  580. when 0 .. 2
  581. "baby"
  582. when 3 .. 6
  583. "little child"
  584. when 7 .. 12
  585. "child"
  586. when 12 .. 18
  587. # Note: 12 already matched by "child"
  588. "youth"
  589. else
  590. "adult"
  591. end
  592. Syntax:
  593.  
  594. case expr
  595. [when expr [, expr]...[then]
  596. expr..]..
  597. [else
  598. expr..]
  599. end
  600. the case expressions are also for conditional execution. Comparisons are done by operator ===. Thus:
  601.  
  602. case expr0
  603. when expr1, expr2
  604. stmt1
  605. when expr3, expr4
  606. stmt2
  607. else
  608. stmt3
  609. end
  610. is basically same to below:
  611.  
  612. _tmp = expr0
  613. if expr1 === _tmp || expr2 === _tmp
  614. stmt1
  615. elsif expr3 === _tmp || expr4 === _tmp
  616. stmt2
  617. else
  618. stmt3
  619. end
  620. Behavior of the === method varies for each Object. See docutmentation for each class.
  621.  
  622. and
  623.  
  624. Examples:
  625.  
  626. test && set
  627. test and set
  628. Syntax:
  629.  
  630. expr `&&' expr
  631. expr `and' expr
  632. Evaluates left hand side, then if the result is true, evaluates right hand side. and is lower precedence alias.
  633.  
  634. or
  635.  
  636. Examples:
  637.  
  638. demo || die
  639. demo or die
  640. Syntax:
  641.  
  642. expr `||' expr
  643. expr or expr
  644. Evaluates left hand side, then if the result is false, evaluates right hand side. or is lower precedence alias.
  645.  
  646. not
  647.  
  648. Examples:
  649.  
  650. ! me
  651. not me
  652. i != you
  653. Syntax:
  654.  
  655. `!' expr
  656. not expr
  657. Returns true if false, false if true.
  658.  
  659. expr `!=' expr
  660. Syntax sugar for !(expr == expr).
  661.  
  662. expr `!~' expr
  663. Syntax sugar for !(expr =~ expr).
  664.  
  665. Range expressions
  666.  
  667. Examples:
  668.  
  669. 1 .. 20
  670. /first/ ... /second/
  671. Syntax:
  672.  
  673. expr `..' expr
  674. expr `...' expr
  675. If range expression appears in any other place than conditional expression, it returns range object from left hand side to right hand side.
  676.  
  677. If range expression appears in conditional expression, it gives false until left hand side returns true, it stays true until right hand side is true. .. acts like awk, ... acts like sed.
  678.  
  679. while
  680.  
  681. Examples:
  682.  
  683. while sunshine
  684. work()
  685. end
  686. Syntax:
  687.  
  688. while expr [do]
  689. ...
  690. end
  691. Executes body while condition expression returns true.
  692.  
  693. while modifier
  694.  
  695. Examples:
  696.  
  697. sleep while idle
  698. Syntax:
  699.  
  700. expr while expr
  701. Repeats evaluation of left hand side expression, while right hand side is true. If left hand side is begin expression, while evaluates that expression at lease once.
  702.  
  703. until
  704.  
  705. Examples:
  706.  
  707. until sunrise
  708. sleep
  709. end
  710. Syntax:
  711.  
  712. until expr [do]
  713. ...
  714. end
  715. Executes body until condition expression returns true.
  716.  
  717. until modifier
  718.  
  719. Examples:
  720.  
  721. work until tired
  722. Syntax:
  723.  
  724. expr until expr
  725. Repeats evaluation of left hand side expression, until right hand side is true. If left hand side is begin expression, until evaluates that expression at lease once.
  726.  
  727. Iterators
  728.  
  729. Examples:
  730.  
  731. [1,2,3].each do |i| print i*2, "\n" end
  732. [1,2,3].each{|i| print i*2, "\n"}
  733. Syntax:
  734.  
  735. method_call do [`|' expr...`|'] expr...end
  736. method_call `{' [`|' expr...`|'] expr...`}'
  737. The method may be invoked with the block (do .. end or {..}). The method may be evaluate back that block from inside of the invocation. The methods that calls back the blocks are sometimes called as iterators. The evaluation of the block from iterator is done by yield.
  738.  
  739. The difference between do and braces are:
  740.  
  741. Braces has stronger precedence. For example:
  742. foobar a, b do .. end # foobar will be called with the block.
  743. foobar a, b { .. } # b will be called with the block.
  744. Braces introduce the nested local scopes, that is newly declared local variables in the braces are valid only in the blocks. For example:
  745. foobar {
  746. i = 20 # local variable `i' declared in the block.
  747. ...
  748. }
  749. print defined? i # `i' is not defined here.
  750. foobar a, b { .. } # it is not valid outside of the block
  751. for
  752.  
  753. Examples:
  754.  
  755. for i in [1, 2, 3]
  756. print i*2, "\n"
  757. end
  758. Syntax:
  759.  
  760. for lhs... in expr [do]
  761. expr..
  762. end
  763. Executes body for each element in the result of expression. for is the syntax sugar for:
  764.  
  765. (expr).each `{' `|' lhs..`|' expr.. `}'
  766. yield
  767.  
  768. Examples:
  769.  
  770. yield data
  771. Syntax:
  772.  
  773. yield `(' [expr [`,' expr...]])
  774. yield [expr [`,' expr...]]
  775. Evaluates the block given to the current method with arguments, if no argument is given, nil is used as an argument. The argument assignment to the block prameter is done just like multiple assignment. If the block is not supplied for the current method, the exception is raised.
  776.  
  777. raise
  778.  
  779. Examples:
  780.  
  781. raise "you lose" # raise RuntimeError
  782. # both raises SyntaxError
  783. raise SyntaxError, "invalid syntax"
  784. raise SyntaxError.new("invalid syntax")
  785. raise # re-raise last exception
  786. Syntax:
  787.  
  788. raise
  789. raise message_or_exception
  790. raise error_type, message
  791. raise error_type, message, traceback
  792. Raises a exception. In the first form, re-raises last exception. In second form, if the argument is the string, creates a new RuntimeError exception, and raises it. If the argument is the exception, raise raises it. In the third form, raise creates a new exception of type error_type, and raises it. In the last form, the third argument is the traceback information for the raising exception in the format given by variable $@ or caller function.
  793.  
  794. The exception is assigned to the variable $!, and the position in the source file is assigned to the $@.
  795.  
  796. The word `raise' is not the reserved word in Ruby. raise is the method of the Kernel module. There is an alias named fail.
  797.  
  798. begin
  799.  
  800. Examples:
  801.  
  802. begin
  803. do_something
  804. rescue
  805. recover
  806. ensure
  807. must_to_do
  808. end
  809. Syntax:
  810.  
  811. begin
  812. expr..
  813. [rescue [error_type,..]
  814. expr..]..
  815. [else
  816. expr..]
  817. [ensure
  818. expr..]
  819. end
  820. begin expression executes its body and returns the value of the last evaluated expression.
  821.  
  822. If an exception occurs in the begin body, the rescue clause with the matching exception type is executed (if any). The match is done by the kind_of?. The default value of the rescue clause argument is the StandardError, which is the superclass of most built-in exceptions. Non-local jumps like SystemExit or Interrupt are not subclass of the StandardError.
  823.  
  824. The begin statement has an optional else clause, which must follow all rescue clauses. It is executed if the begin body does not raise any exception.
  825.  
  826. For the rescue clauses, the error_type is evaluated just like the arguments to the method call, and the clause matches if the value of the variable $! is the instance of any one of the error_type of its subclass. If error_type is not class nor module, the rescue clause raises TypeError exception.
  827.  
  828. If ensure clause given, its clause body executed whenever beginbody exits.
  829.  
  830. retry
  831.  
  832. Examples:
  833.  
  834. retry
  835. Syntax:
  836.  
  837. retry
  838. If retry appears in rescue clause of begin expression, restart from the beginning of the 1begin body.
  839.  
  840. begin
  841. do_something # exception raised
  842. rescue
  843. # handles error
  844. retry # restart from beginning
  845. end
  846. If retry appears in the iterator, the block, or the body of the for expression, restarts the invocation of the iterator call. Arguments to the iterator is re-evaluated.
  847.  
  848. for i in 1..5
  849. retry if some_condition # restart from i == 1
  850. end
  851. # user defined "until loop"
  852. def UNTIL(cond)
  853. yield
  854. retry if not cond
  855. end
  856. retry out of rescue clause or iterators raises exception.
  857.  
  858. return
  859.  
  860. Examples:
  861.  
  862. return
  863. return 12
  864. return 1,2,3
  865. Syntax:
  866.  
  867. return [expr[`,' expr...]]
  868. Exits from method with the return value. If more than two expressions are given, the array contains these values will be the return value. If no expression given, nil will be the return value.
  869.  
  870. break
  871.  
  872. Examples:
  873.  
  874. i=0
  875. while i<3
  876. print i, "\n"
  877. break
  878. end
  879. Syntax:
  880.  
  881. break
  882. Exits from the most internal loop. Notice break does not exit from case expression like C.
  883.  
  884. next
  885.  
  886. Examples:
  887.  
  888. next
  889. Syntax:
  890.  
  891. next
  892. Jumps to next iteration of the most internal loop.
  893.  
  894. redo
  895.  
  896. Examples:
  897.  
  898. redo
  899. Syntax:
  900.  
  901. redo
  902. Restarts this iteration of the most internal loop, without checking loop condition.
  903.  
  904. BEGIN
  905.  
  906. Examples:
  907.  
  908. BEGIN {
  909. ...
  910. }
  911. Syntax:
  912.  
  913. BEGIN '{'
  914. expr..
  915. '}'
  916. Registers the initialize routine. The block followed after BEGIN is evaluated before any other statement in that file (or string). If multiple BEGIN blocks are given, they are evaluated in the appearing order.
  917.  
  918. The BEGIN block introduce new local-variable scope. They don't share local variables with outer statements.
  919.  
  920. The BEGIN statement can only appear at the toplevel.
  921.  
  922. END
  923.  
  924. Examples:
  925.  
  926. END {
  927. ...
  928. }
  929. Syntax:
  930.  
  931. END '{' expr.. '}'
  932. Registers finalize routine. The block followed after END is evaluated just before the interpreter termination. Unlike BEGIN, END blocks shares their local variables, just like blocks.
  933.  
  934. The END statement registers its block only once at the first execution. If you want to register finalize routines many times, use at_exit.
  935.  
  936. The END statement can only appear at the toplevel. Also you cannot cancel finalize routine registered by END.
  937.  
  938. Class definitions
  939.  
  940. Examples:
  941.  
  942. class Foo < Super
  943. def test
  944. :
  945. end
  946. :
  947. end
  948. Syntax:
  949.  
  950. class identifier [`<' superclass ]
  951. expr..
  952. end
  953. Defines the new class. The class names are identifiers begin with uppercase character.
  954.  
  955. Singleton-class definitions
  956.  
  957. Examples:
  958.  
  959. class << obj
  960. def test
  961. :
  962. end
  963. :
  964. end
  965. Syntax:
  966.  
  967. class `<<' expr
  968. expr..
  969. end
  970. Defines the class attribute for certain object. The definitions within this syntax only affect the specified object.
  971.  
  972. Module definitions
  973.  
  974. Examples:
  975.  
  976. module Foo
  977. def test
  978. :
  979. end
  980. :
  981. end
  982. Syntax:
  983.  
  984. module identifier
  985. expr..
  986. end
  987. Defines the new module The module names are identifiers begin with uppercase character.
  988.  
  989. Method definitions
  990.  
  991. Examples:
  992.  
  993. def fact(n)
  994. if n == 1 then
  995. 1
  996. else
  997. n * fact(n-1)
  998. end
  999. end
  1000. Syntax:
  1001.  
  1002. def method_name [`(' [arg ['=' default]]...[`,' `*' arg ]`)']
  1003. expr..
  1004. end
  1005. Defines the new method. Method_name should be either identifier or re-definable operators (e.g. ==, +, -, etc.). Notice the method is not available before the definition. For example:
  1006.  
  1007. foo
  1008. def foo
  1009. print "foo\n"
  1010. end
  1011. will raise an exception for undefined method invoking.
  1012. The argument with default expression is optional. The evaluation of the default expression is done at the method invocation time. If the last argument preceded by *, actual parameters which don't have corresponding formal arguments are assigned in this argument as an array.
  1013.  
  1014. If the last argument preceded by &, the block given to the method is converted into the Proc object, and assigned in this argument. In case both * and & are present in the argument list, & should come later.
  1015. The method definitions can not be nested.
  1016.  
  1017. The return value of the method is the value given to the return, or that of the last evaluated expression.
  1018.  
  1019. Some methods are marked as `private', and must be called in the function form.
  1020.  
  1021. When the method is defined outside of the class definition, the method is marked as private by default. On the other hand, the methods defined in the class definition are marked as public by default. The default visibility and the `private' mark of the methods can be changed by public or private of the Module.
  1022.  
  1023. In addition, the methods named initialize are always defined as private methods.
  1024.  
  1025. Singleton-method definitions
  1026.  
  1027. Examples:
  1028.  
  1029. def foo.test
  1030. print "this is foo\n"
  1031. end
  1032. Syntax:
  1033.  
  1034. def expr `.' identifier [`(' [arg [`=' default]]...[`,' `*' arg ]`)']
  1035. expr..
  1036. end
  1037. The singleton-method is the method which belongs to certain object. The singleton-method definitions can be nested.
  1038.  
  1039. The singleton-methods of classes inherited to its subclasses. The singleton-methods of classes are acts like class methods in other object-oriented languages.
  1040.  
  1041. alias
  1042.  
  1043. Examples:
  1044.  
  1045. alias foo bar
  1046. alias $MATCH $&
  1047. Syntax:
  1048.  
  1049. alias method-name method-name
  1050. alias global-variable-name global-variable-name
  1051. Gives alias to methods or global variables. Aliases can not be defined within the method body.
  1052.  
  1053. The aliase of the method keep the current definition of the method, even when methods are overridden.
  1054.  
  1055. Making aliases for the numbered global variables ($1, $2,...) is prohibited. Overriding the builtin global variables may cause serious problems.
  1056.  
  1057. undef
  1058.  
  1059. Examples:
  1060.  
  1061. undef bar
  1062. Syntax:
  1063.  
  1064. undef method-name
  1065. Cancels the method definition. Undef can not appear in the method body. By using undef and alias, the interface of the class can be modified independently from the superclass, but notice it may be broke programs by the internal method call to self.
  1066.  
  1067. defined?
  1068.  
  1069. Examples:
  1070.  
  1071. defined? print
  1072. defined? File.print
  1073. defined?(foobar)
  1074. defined?($foobar)
  1075. defined?(@foobar)
  1076. defined?(Foobar)
  1077. Syntax:
  1078.  
  1079. defined? expr
  1080. Returns false if the expression is not defined. Returns the string that describes a kind of the expression.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement