1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

* doc/syntax.rdoc: Added syntax guide table of contents

* doc/syntax/exceptions.rdoc:  Syntax guide for exceptions
* doc/syntax/literals.rdoc:  Syntax guide for literals
* doc/syntax/methods.rdoc:  Syntax guide for methods


git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38419 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
drbrain 2012-12-17 02:26:15 +00:00
parent 810008293f
commit 29fd593475
5 changed files with 512 additions and 0 deletions

View file

@ -1,3 +1,10 @@
Mon Dec 17 11:25:32 2012 Eric Hodel <drbrain@segment7.net>
* doc/syntax.rdoc: Added syntax guide table of contents
* doc/syntax/exceptions.rdoc: Syntax guide for exceptions
* doc/syntax/literals.rdoc: Syntax guide for literals
* doc/syntax/methods.rdoc: Syntax guide for methods
Mon Dec 17 07:59:40 2012 Eric Hodel <drbrain@segment7.net>
* lib/rubygems.rb: Updated VERSION

13
doc/syntax.rdoc Normal file
View file

@ -0,0 +1,13 @@
= Ruby Syntax
The Ruby syntax is large and is split up into the following sections:
Literals[rdoc-ref:doc/syntax/literals.rdoc] ::
Numbers, Strings, Arrays, Hashes, etc.
Methods[rdoc-ref:doc/syntax/methods.rdoc] ::
Method and method argument syntax
Exceptions[rdoc-ref:doc/syntax/exceptions.rdoc] ::
Exception handling syntax

View file

@ -0,0 +1,79 @@
= Exception Handling
Exceptions are rescued in a +begin+/+end+ block:
begin
# code that might raise
rescue
# handle exception
end
If you are inside a method you do not need to use +begin+ or +end+ unless you
wish to limit the scope of rescued exceptions:
def my_method
# ...
rescue
# ...
end
The same is true for a +class+ or +module+.
You can assign the exception to a local variable by using <tt>=>
variable_name</tt> at the end of the +rescue+ line:
begin
# ...
rescue => exception
warn exception.message
raise # re-raise the current exception
end
By default StandardError and its subclasses are rescued. You can rescue a
specific set of exception classes (and their subclasses) by listing them after
+rescue+:
begin
# ...
rescue ArgumentError, NameError
# handle ArgumentError or NameError
end
You may rescue different types of exceptions in different ways:
begin
# ...
rescue ArgumentError
# handle ArgumentError
rescue NameError
# handle NameError
rescue
# handle any StandardError
end
The exception is matched to the rescue section starting at the top, and matches
only once. If an ArgumentError is raised in the begin section it will not be
handled in the StandardError section.
To always run some code whether an exception was raised or not, use +ensure+:
begin
# ...
rescue
# ...
ensure
# this always runs
end
You may also run some code when an exception is not raised:
begin
# ...
rescue
# ...
else
# this runs only when no exception was raised
ensure
# ...
end

283
doc/syntax/literals.rdoc Normal file
View file

@ -0,0 +1,283 @@
= Literals
Literals create objects you can use in your program. Literals include:
* Booleans and nil
* Numbers
* Strings
* Symbols
* Arrays
* Hashes
* Ranges
* Regular Expressions
* Procs
== Booleans and nil
+nil+ and +false+ are both false values. +nil+ is sometimes used to indicate
"no value" or "unknown" but evaluates to +false+ in conditional expressions.
+true+ is a true value. All objects except +nil+ and +false+ evaluate to a
true value in conditional expressions.
(There are also the constants +TRUE+, +FALSE+ and +NIL+, but the lowercase
literal forms are preferred.)
== Numbers
You can write integers of any size as follows:
1234
1_234
These numbers have the same value, 1,234. The underscore may be used to
enhance readability for humans. You may place an underscore anywhere in the
number.
Floating point numbers may be written as follows:
12.34
1234e-2
1.234E1
These numbers have the same value, 12.34. You may use underscores in floating
point numbers as well.
You can also write numbers in hexadecimal, octal or binary formats. For
hexadecimal numbers use a prefix of <tt>0x</tt>, for octal numbers use a
prefix of <tt>0</tt>, for binary numbers use a prefix of <tt>0b</tt>. The
alphabetic component of the number is not case-sensitive. Examples:
0xaa
0xAa
0xAA
0Xaa
0XAa
0XaA
0252
0b10101010
0B10101010
All these numbers have the same decimal value, 170. Like integers and floats
you may use an underscore for readability.
== Strings
The most common way of writing strings is using <tt>"</tt>:
"This is a string".
The string may be many lines long.
Any internal <tt>"</tt> must be escaped:
"This string has a quote: \". As you can see, it is escaped"
Double-quote strings allow escaped characters such as <tt>\n</tt> for newline,
<tt>\t</tt> for tab, etc.
Double-quote strings allow interpolation of other values using
<tt>#{...}</tt>:
"One plus one is two: #{1 + 1}"
Any expression may be placed inside the interpolated section, but it's best to
keep the expression small for readability.
Interpolation may be disabled by escaping the "#" character or using
single-quote strings:
'#{1 + 1}' #=> "\#{1 + 1}"
In addition to disabling interpolation, single-quoted strings also disable all
escape sequences except for the single-quote (<tt>\'</tt>).
You may also create strings using <tt>%</tt>:
%(1 + 1 is #{1 + 1}) #=> "1 + 1 is 2"
There are two different types of <tt>%</tt> strings <tt>%q(...)</tt> behaves
like a single-quote string (no interpolation or character escaping) while
<tt>%Q</tt> behaves as a double-quote string. See Percent Strings below for
more discussion of the syntax of percent strings.
=== Here Documents
If you are writing a large block of text you may use a "here document" or
"heredoc":
expected_result = <<HEREDOC
This would contain specially formatted text.
That might span many lines
HEREDOC
The heredoc starts on the line following <tt><<HEREDOC</tt> and ends with the
next line that starts with <tt>HEREDOC</tt>. The result includes the ending
newline.
You may use any identifier with a heredoc, but all-uppercase identifiers are
typically used.
You may indent the ending identifier if you place a "-" after <tt><<</tt>:
def test_something
expected_result = <<-INDENTED_HEREDOC
This would contain specially formatted text.
That might span many lines
INDENTED_HEREDOC
# ...
end
Note that the while the closing identifier may be indented, the content is
always treated as if it is flush left. If you indent the content those spaces
will appear in the output.
A heredoc allows interpolation and escaped characters. You may disable
interpolation and escaping by surrounding the opening identifier with single
quotes:
expected_result = <<-'EXPECTED'
One plus one is #{1 + 1}
EXPECTED
p expected_result # prints: "One plus one is \#{1 + 1}\n"
To call a method on a heredoc place it after the opening identifier:
expected_result = <<-EXPECTED.chomp
One plus one is #{1 + 1}
EXPECTED
You may open multiple heredocs on the same line, but this can be difficult to
read:
puts(<<-ONE, <<-TWO)
content for heredoc one
ONE
content for heredoc two
TWO
== Symbols
A Symbol represents a name inside the ruby interpreter. See Symbol for more
details on what symbols are and when ruby creates them internally.
You may reference a symbol using a colon: <tt>:my_symbol</tt>.
You may also create symbols by interpolation:
:"my_symbol1"
:"my_symbol#{1 + 1}"
Note that symbols are never garbage collected so be careful when referencing
symbols using interpolation.
Like strings, a single-quote may be used to disable interpolation:
:"my_symbol#{1 + 1}" #=> :"my_symbol\#{1 + 1}"
When creating a Hash there is a special syntax for referencing a Symbol as
well.
== Arrays
An array is created using the objects between <tt>[</tt> and <tt>]</tt>:
[1, 2, 3]
You may place expressions inside the array:
[1, 1 + 1, 1 + 2]
[1, [1 + 1, [1 + 2]]]
See Array for the methods you may use with an array.
== Hashes
A hash is created using key-value pairs between <tt>{</tt> and <tt>}</tt>:
{ "a" => 1, "b" => 2 }
Both the key and value may be any object.
You can create a hash using symbol keys with the following syntax:
{ a: 1, b: 2 }
This same syntax is used for keyword arguments for a method.
See Hash for the methods you may use with a hash.
== Ranges
A range represents an interval of values. The range may include or exclude
its ending value.
(1..2) # includes its ending value
(1...2) # excludes its ending value
You may create a range of any object. See the Range documentation for details
on the methods you need to implement.
== Regular Expressions
A regular expression is created using "/":
/my regular expression/
The regular expression may be followed by flags which adjust the matching
behavior of the regular expression. The "i" flag makes the regular expression
case-insensitive:
/my regular expression/i
Interpolation may be used inside regular expressions along with escaped
characters. Note that a regular expression may require additional escaped
characters than a string.
See Regexp for a description of the syntax of regular expressions.
== Procs
A proc can be created with <tt>-></tt>:
-> { 1 + 1 }
Calling the above proc will give a result of <tt>2</tt>.
You can require arguments for the proc as follows:
->(v) { 1 + v }
This proc will add one to its argument.
== Percent Strings
Besides <tt>%(...)</tt> which creates a String, The <tt>%</tt> may create
other types of object. As with strings, an uppercase letter allows
interpolation and escaped characters while a lowercase letter disables them.
These are the types of percent strings in ruby:
<tt>%i</tt> :: Array of Symbols
<tt>%q</tt> :: String
<tt>%r</tt> :: Regular Expression
<tt>%s</tt> :: Symbol
<tt>%w</tt> :: Array of Strings
<tt>%x</tt> :: Backtick (capture subshell result)
For the two array forms of percent string, if you wish to include a space in
one of the array entries you must escape it with a "\\" character:
%w[one one-hundred\ one]
#=> ["one", "one-hundred one"]
If you are using "(", "[", "{", "<" you must close it with ")", "]", "}", ">"
respectively. You may use most other non-alphanumeric characters for percent
string delimiters such as "%", "|", "^", etc.

130
doc/syntax/methods.rdoc Normal file
View file

@ -0,0 +1,130 @@
= Methods
Methods implement the functionality of your program. Here is a simple method
definition:
def one_plus_one
1 + 1
end
A method definition consists of the +def+ keyword, a method name, the body of
the method, then the +end+ keyword. When called the method will execute the
body of the method. This method returns <tt>2</tt>.
== Arguments
A method may accept arguments. The argument list follows the method name:
def add_one(value)
value + 1
end
When called, the user of the +add_one+ method must provide an argument. The
argument is a local variable in the method body. The method will then add one
to this argument and return the value. If given <tt>1</tt> this method will
return <tt>2</tt>.
The parentheses around the arguments are optional:
def add_one value
value + 1
end
Multiple arguments are separated by a comma:
def add_values(a, b)
a + b
end
When called, the arguments must be provided in the exact order. In other
words, the arguments are positional.
=== Default Values
Arguments may have default values:
def add_values(a, b = 1)
a + b
end
The default value does not need to appear first, but the must be grouped
together. This is ok:
def add_values(a = 1, b = 2, c)
a + b + c
end
This will raise a SyntaxError:
def add_values(a = 1, b, c = 1)
a + b + c
end
=== Keyword Arguments
Keyword arguments are similar to positional arguments with default values:
def add_values first: 1, second: 2
first + second
end
When calling a method with keyword arguments the arguments may appear in any
order. If an unknown keyword argument is sent by the caller an ArgumentError
is raised.
When mixing keyword arguments and positional arguments, all positional
arguments must appear before any keyword arguments.
=== Array/Hash Argument
Prefixing an argument with "*" causes any remaining arguments to be converted
to an Array:
def gather_arguments(*arguments)
p arguments
end
gather_arguments 1, 2, 3 # prints [1, 2, 3]
The array argument must be the last positional argument, it must appear before
any keyword arguments.
The array argument will capture a Hash as the last entry if a hash was sent by
the caller after all positional arguments.
gather_arguments 1, a: 2 # prints [1, {:a=>2}]
However, this only occurs if the method does not declare any keyword arguments.
def gather_arguments_keyword(*positional, keyword: nil)
p positinal: positional, keyword: keyword
end
gather_arguments_keyword 1, 2, three: 3
#=> raises: unknown keyword: three (ArgumentError)
== Exception Handling
Methods have an implied exception handling block so you do not need to use
+begin+ or +end+ to handle exceptions. This:
def my_method
begin
# code that may raise an exception
rescue
# handle exception
end
end
May be written as:
def my_method
# code that may raise an exception
rescue
# handle exception
end
If you wish to rescue an exception for only part of your method use +begin+ and
+end+. For more details see the page on {Exception
Handling}[rdoc-ref:doc/syntax/exceptions.rdoc].