ruby syntax tutorials

sponsored links
The first part of the Ruby language based

Chapter § 1.1 Ruby Ruby language overview of the history
Ruby language is Japanese inventor Yukihiro Matsumoto (Matsumoto Yukihiro), we affectionately called him "Matz".
May be contrary to everyone's surprise, Ruby is not a recent occurrence in the birth of language, its history dates back to 1993, Ruby began the father of Matz interested in scripting language. Through some analysis and reflection, Matz scripting language that can become very powerful and flexible, so he prepared to scripting language as his direction. Like most people, Matz is an object-oriented programming fans, naturally he wanted to study a support object-oriented programming scripting language. Following a period of time, he went to search the Internet, some relevant information, and found a Perl 5, Perl 5 was not released. Understanding through a period of time after, Matz. Found that Perl 5 is not what he wanted, so he gave up the Perl script as an object-oriented languages use the idea. Matz then turned to Python, Python is an interpreted, object-oriented language, but Matz found that Python can not fully count as "object oriented" language. Matz that Python is object oriented and procedural programming language (Procedural Programming Language) in the mixed product. Matz hoped to find a more powerful than Perl, more than the object-oriented language Python, but unfortunately, such language does not exist on Earth at that time. Matz was his intention to design a new programming language. February 24, 1993 was a memorable day, Ruby was born on this day. Matz in December 1995 launched the first version of Ruby Ruby 0.95. Before 1996, are Matz. A person in the development for Ruby development. Later, with the Ruby community gradually formed, and many community members to a number of significant help Matz, including the submission of bug and patch, etc.. Now, Ruby, like other open source projects, have their own development team, the ability of any individual or group can participate in the development and evolution of Ruby.

§ 1.2 Ruby origin of the name first of all be clear, Ruby is not the initials of other words. By Perl impact, Matz also like to use a Stone to name his new language, he used one of his colleagues in the zodiac stones - ruby. Later, Matz Ruby realized the name is appropriate, first of all, the Zodiac stone, Pearl representatives in June, and July on behalf of Ruby. The font size, Pearl size is 5pt, ruby the size of 5.5pt. So the name for a kind of Ruby Perl language is appropriate follow-up.

§ 1.3 Ruby features
Ruby is a powerful object-oriented scripting language, you can use it quickly and easily object-oriented programming. Similar with Perl, and Ruby has powerful text processing capabilities, so that simple text processing. In addition, you can easily use the C language to extend Ruby's features.
If you have, "like a simple object-oriented language" or that "Perl's features, while useful, but it can not stand the syntax of real people," or that "LISP family of languages thought good, but brackets everywhere really annoying, at least according to the usual style formula should be written. " Then, Ruby might make you satisfied.

To sum up, Ruby has the following advantages:
 interpreted execution, convenient
Ruby is an interpreted language, the program can be executed without compilation.
 syntax is simple, elegant and simple syntax, similar to the Algol system syntax.
 fully object-oriented
Ruby was designed from the outset as a purely object-oriented language, so everything is an object, such as integers and other basic data types.
 Built-in regular engine for text processing
Ruby supports a powerful string handling and regular expression search function, can easily be handled on a string.
 Automatic garbage collection is garbage collection (Garbage Collect, GC) function that can no longer use recycled objects. Does not require users to manage memory.
 and a high degree of cross-platform portability
Ruby supports multiple platforms, in Windows, Unix, Linux, MacOS, both can run. Ruby programs are very good portability, most programs can without modification of the various platforms to run.
 elegant, perfect exception handling mechanism
Ruby provides a set of exception handling mechanisms, the code can easily handle errors gracefully handle the situation.
 has many advanced features
Ruby has many advanced features, such as operator overloading, Mix-ins, special methods, etc., is to use these features can easily complete a variety of powerful features.

At the same time, because it is interpreted language, Ruby has the following disadvantages:
 interpreted language, so slow  less static checking § 1.4 Ruby and Python comparison
Python is a Ruby's rival. His profound skill, can be described as "the Millennium snake demon." However, that Python functions matz not perfect, otherwise they will not create a Ruby.

Chapter II § 2.1 Ruby Ruby programming environment installation
Ruby supports multiple platforms, including Windows, Linux, various class UNIX, MacOS X and so on.
§ 2.1.1 to install Ruby on Windows 95/98/Me/XP
Using the Windows platform for users to install Ruby is quite simple and straightforward matter. The most convenient way is to use the "One-Click Ruby Installer".
I wonder if you have not heard about SourceForge? SourceForge is the world's largest open source software development platform and the warehouse. It integrates many open source applications, to provide a complete software development life cycle services. In the Ruby world, there is a similar site, that is Rubyforge. "One-Click Ruby Installer" is Rubyforge on an open source project, is Rubyforge download one of the largest. The project will be the core Ruby language and a set of common extensions integrated together, also includes support for Ruby's free IDE tools FreeRIDE and SciTE, in addition to these include help documentation, sample code, RubyGems package manager, Fox GUI library, fxri (Interactive Ruby Help & Console) so. And as it name implies, use it, Ruby has become an unprecedented ease of installation. You can download the following address to its latest version:
http://rubyforge.org/projects/rubyinstaller/
§ 2.1.2 to install Ruby on Linux
Ruby under the linux installation is slightly more complex, recommended way to install the compiled source code, so you can guarantee install the latest version.
First of all, to the ruby master http://www.ruby-lang.org/en/ download the source code, extract to the directory after the download is complete, then use the following command:
. / Configure
. / Make; make install
Implementation of the above command requires root privileges, the default installation to / usr / local following. You can also use the ". / Configure - prefix = custom path" to specify the installation directory.
windows on a ruby one-click installer default install RubyGems, but in Linux, we need to manually install RubyGems. RubyGems is a Ruby package manager, we will be talked about behind it.
First, from the Rubyforge download the latest version of RubyGems the following address:
http://rubyforge.org/projects/rubygems/
After extracting RubyGems to the appropriate directory by typing ruby setup.rb, screen print some of the log will tell you after the installation is successful, the implementation of gem-v to see gem install the version number.
§ 2.2 to run Ruby
Below, we will under the Windows platform environment, for example how to run Ruby Ruby.
§ 2.2.1 using Ruby

The "Hello World" as the first school to learn computer language to write the program has now become a tradition. The program first appeared in the Brian Kernighan and Dennis Ritchie wrote the classic computer programming tutorial "The C Programming Language". We take a look at Ruby World "Hello World":

In Windows, open a command prompt window, at the prompt, enter "Ruby" and press Enter, Ruby interpreter will be running and wait for input process. Ruby executable search path should be included within the system.
Enter the following procedures:

print "Hello World!"

And then press Ctrl + D and press enter, you will see Ruby implementation of the program output:

You can also save first code file, then use the re-implementation of Ruby interpreter:

§ 2.2.2 using FreeRIDE and SciTE
FreeRIDE is a free IDE support for Ruby language environments. FreeRIDE itself is using the Ruby language development, it is also one of the important Rubyforge.
You can use FreeRIDE debugging and implementation of Ruby to write code, FreeRIDE built into the environment and the Ruby language interactive online help, is very powerful.

Scintilla is a free source code editing control, it is fully open source, and allows users to freely use open source software or commercial software. SciTE is an editor of this control software developed in the "One-Click Ruby Installer" in, SciTE integrated Ruby language support, ease of use. Compared FreeRIDE, it is easy to use features.

§ 2.2.3 using fxri
Fxri is a Ruby interactive tools to help and console. It not only can be used as the language of online help, and the interactive Ruby interpreter can be used to perform procedures. For learning Ruby language, fxri is a very handy helper.
I wonder if you have not heard Fox ToolKit, it is very lightweight open source graphics library. FXRuby is a project on RubyForge, provides Ruby language interface to use Fox ToolKit. The Fxri is developed based on FXRuby, Fxri same items on RubyForge. So you should be able to guess the origin of the name  Fxri

Fxri also integrates Ruby-irb and Ruby-ri features, with it, you can give Ruby-irb, Ruby-ri, but if you are not using Windows system, then I did not count 
§ 2.3 Ruby-irb
Ruby-irb is the interactive Ruby (Interactive Ruby) short, to read from standard input and execute Ruby code into a tool, like a shell.
Use the command "irb" into the interactive mode, then you can enter the command line command like Ruby code as input, the code execution results will immediately show:

§ 2.4 Ruby-ri
And, like Perl, Ruby also designed the embedded document. ruby-ri is the tool to view the document. Ruby-ri in the implementation of the orders for the "ri", for example, you can "ri String.new" to query the new method of String class:

§ 2.5 RubyGems
RubyGems is the Ruby community popular package management tool, in the past if you want to download a Ruby extension or application, you first need to download the appropriate zip package, and then decompress and then install the Ruby application or extend the corresponding directory. But with all these problems are not RubyGems, you just need a command from a remote server, you can download the appropriate package, if the corresponding application contains other extensions, RubyGems will prompt you to install the dependency from a remote extension. Installed RubyGems will run the corresponding program to help generate rdoc documentation. Of course, you can also download the package to the local running RubyGems local installation command.
Unified management of the benefits is simple, with the RubyGems package manager, Ruby applications never seen before will become easy to install. RubyGems is Rubyforge download one of the largest, and now Ruby community, applications are moving in the direction of RubyGems, RubyGems Ruby will become the de facto standard package manager.
RubyGems package manager executable command is "gem", gem command contains many sub-commands and the appropriate options, such as:
gem -h/--help - Display command help
gem -v/--version - shows the version number of Gems

Classes and Objects Chapter
Ruby is a true object oriented programming language, object oriented refers to the object-centered theories.
 package (Encapsulation)
To hide the internal structures and algorithms, to ensure that only specific processes (also called methods) to directly manipulate the data, the results can not directly use the data structure from the outside, while the internal structure changes once will not have adverse impact on the outside. This isolation method is called encapsulation.
  inheritance polymorphism (Polymorphism)
According to the different object select the appropriate action. The implementation method in Ruby is to be adjusted according to the different objects to choose different methods.

Although many languages are claimed to be object-oriented, but they often object-oriented interpretation of the same, mostly based on their own unique way to explain what object-oriented, but in reality, the object-oriented language they use a lot of non-object-oriented approach.
To Java as an example: If you want to take a number to take absolute value, java practice:
int num = Math.abs (-99);
Is a value passed to the Math class, a static function abs processing. Why do this? Because in java, the value is not the kind of basic types.
In Ruby, everything is an object, that is, the number -99 is the object, taking the absolute value of such an operation should belong to the figure itself, so Ruby's approach is to:
c =-99.abs
In Ruby, you are the object of all operations, results of operations is also an object.
§ 3.1 Class definition class is to have the same properties and behavior of the object as an abstract, Ruby in the class declaration using the class keyword. The syntax for the definition of class is as follows,
class ClassName
def method_name (variables)
# Some code
end
end
The definition of class in class ... end, between the above format, ClassName is the class name, class name must begin with a capital letter, ie the class name if the one constant.

See the following example:
class Person
def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
end
end

If a class has been defined before, this time they were carried out with the same class if the class definition, it means that the original definition of additional classes.

class Test
def meth1
puts "This is meth1"
end
end

class Test
def meth2
puts "This is meth2"
end
end

Test class in the original meth1 method, we added meth2 method, this time for the Test class of objects, meth1 and meth2 are also available.
§ 3.2 objects, properties and methods of class formation in the instantiated object, the object in the attribution of a specific type of stress, sometimes we use the term instance of an object.
Method (Method) is the object of the operation. Operation object (was transferred) to self to express. In Ruby, remove the object within the class, the general structure of the object is dynamically determined. The nature of an object defined by its internal decision method.
See the following example, we use new methods to create a new object,

class Person
def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
end
end
people = Person.new ('Tom', 'male', 15)

We can use Person.new method to create a Person class instance object. Heading to @ variable is an instance variable, they are subordinate to an instance of an object, Ruby instance variables in the name of the variable naming rules to @ start, you can only use it internally in the method.
method to initialize the object into a "ready" state, initialize method is a special method, this method will construct an instance of an object is automatically called.
Initialization of the instance, the need to redefine initialize method. Class method new default behavior is to generate the instance of the implementation of the new initialize method, the parameters passed to new methods will be passed to initialize method intact. In addition, if called with block, the block will be passed to initialize method. Therefore, the need of the new method is redefined.
In Ruby, instance variables only way to operate, it can be said that Ruby's package is mandatory. To the object can not directly access, only access through the interface method.

class Person
def name
@ Name
end

def gender
@ Gender
end

def age
@ Age
end
end

people = Person.new ('Tom', 'male', 15)
puts people.name
puts people.gender
puts people.age

Output:
Tom
male
15

In Ruby, an object's internal attributes are private. The above code, we define the method name, gender, age three methods used to access the Person class instance object instance variables. Note name, gender, age appropriate access to instance variables can only read, not change their values.

We can also meet with members of the variable read-only control attr_reader to achieve the same effect.
class Person
attr_reader: name,: gender,: age
end

Similarly, we can define a method to change the member variable value.
class Person
def name = (name)
@ Name = name
end

def gender = (gender)
@ Gender = gender
end

def age = (age)
@ Age = age
end
end
people = Person.new ('Tom', 'male', 15)
people.name = "Henry"
people.gender = "male"
people.age = 25

Member variables can also be used to write control character attr_writer to achieve the same effect.
class Person
attr_writer: name,: gender,: age
end

We can also use the member variable attr_accessor to illustrate both read, write.
class Person
attr_accessor: name,: gender,: age
end

You can also use the variable attr control operator to control whether the read and write. attr parameter can only take a symbol, the second parameter is a bool parameter that indicates whether the write method produces symbolic parameters. Its default value is false, generate only read method, do not produce written method.
class Person
attr: name, true # to read and write
attr: gender, true # to read and write
attr: age, true # to read and write
attr: id, false # read-only
end

Note attr_reader, attr_writer, attr_accessor and attr not language keywords, but Module modules.

class Test
attr_accessor: value
end
puts Test.instance_methods - Test.superclass.public_methods

Implementation of the results:
value
value =

The code above, we use Test.instance_methods be an instance of Test class for all methods, Test.superclass.public_methods get parent class of all instances of Test Methods, and then subtract to get Test class does not contain all of the instances of the parent class method.
As instance_methods method returns a value of an Array, so we make the difference operation, Array of the specific operation will be mentioned later chapters.

Can also be re-defined methods, re-define a method, the new definition will override the original definition.

The following example re-define class method meth1,
class Test
def meth1
puts "This is meth1"
end
end

a = Test.new
a.meth1

class Test
def meth1
puts "This is new meth1"
end
end

a. meth1

Implementation of the results:
This is meth1
This is new meth1

Re-define the same class, the definition means that the original complement, not override the original definition. The re-defined method, it will overwrite the original definition.

We can use their own self identity, self, and Java in this somewhat similar, representing the current object.
class Person
def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
end

def <=> (other)
self.age <=> other.age
end
end

<=> Method is usually meant for comparison, the return value is -1,0 or 1, respectively, less than, equal to and greater than.
§ 3.3 Inheritance
Ruby inheritance syntax is very simple to use <can.
class Student <Person
def initialize (name, gender, age, school)
@ Name = name
@ Gender = gender
@ Age = age
@ School = school
end
end

Ruby language only supports single inheritance, each class can have only one direct parent. This avoids the complexity of multiple inheritance. But at the same time, Ruby provides a mechanism for mixin can be used to achieve multiple inheritance.

Can use the super keyword calls the parent class method object, when the super omitted parameters, the parameters will be used to carry out the current method call.
class Base
def meth (info)
puts "This is Base # (info)"
end
end

class Derived <Base
def meth (info)
puts "This is derived # (info)"
super
end
end

obj1 = Derived.new
obj1.meth ("test")

Implementation of the results:
This is derived test
This is Base test

If the incoming parameter is modified and then call the super, then will be used to use the modified value.

class Base
def meth (info)
puts "This is Base # (info)"
end
end

class Derived <Base
def meth (info)
puts "This is derived # (info)"
info = "over"
super
end
end

obj1 = Derived.new
obj1.meth ("test")

Implementation of the results:
This is derived test
This is Base over
§ 3.4 Special methods and special class special method is unique to a particular instance of the method. An object which acts from the right to determine their class, but sometimes, some special objects, like any other object does not act, in most programming languages, such as C + + and Java, we must define a new class, but In Ruby, we can define a specific object only way affiliated with this method we have become a special method (Singleton Method).

class SingletonTest
def info
puts "This is This is SingletonTest method"
end
end

obj1 = SingletonTest.new
obj2 = SingletonTest.new

def obj2.info
puts "This is obj2"
end

obj1.info
obj2.info

Implementation of the results:
This is This is SingletonTest method
This is obj2

Sometimes, we need to define an object a number of special methods, if the previous method, then only one definition:

def obj2.singleton_method1
end

def obj2.singleton_method2
end

def obj2.singleton_method3
end
... ...
def obj2.singleton_methodn
end

This is very complex problems, and can not give a unified conceptual model, so Ruby provides another way,
class <<obj
... ...
end

obj is a specific object instance, class <<on behalf of its special class.

class SingletonTest
def meth1
puts "This is meth1"
end

def meth2
puts "This is meth2"
end
end

obj1 = SingletonTest.new
obj2 = SingletonTest.new

class <<obj2
def meth1
puts "This is obj2's meth1"
end

def meth2
puts "This is obj2's meth2"
end
end

obj1.meth1
obj1.meth2
obj2.meth1
obj2.meth2

Implementation of the results:
This is meth1
This is meth2
This is obj2's meth1
This is obj2's meth2

§ 3.5 Class variables and class methods class variables are all instances of a class of objects shared by class methods can also be accessed. Class variable names start with'@@',, such as '@ @ number'. And global variables, instance variables, class variables must be initialized before use:
class Person
@ @ Number = 0 # initial value before use must be
def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
@ @ Number + = 1
end
end

Class variables are private, outside the class can not directly access, you can only instance methods and class methods to access it.

Similarly, the class is part of a class method, when the definition of class method with the class name before the method:
class Person
@ @ Number = 0

def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
@ @ Number + = 1
end

def Person.getNumber # class method
return @ @ number
end
end

In addition to the definition of class method Person.getNumber this way, it also can use other means defined class method, you can gradually see in later chapters.

§ 3.4 Access Control When you design a class, you need to decide what properties and methods can be accessed outside the class, what properties and methods outside the class is hidden. If a class has too many properties and methods can be accessed outside the class to, then bound to destroy this class encapsulation. Fortunately, in Ruby, the only way to change through a class of property, so we only need to consider the method of access control.
There are three methods of access control:
 public methods (Public Method)
 method can be called from anywhere, which is the default method of access control. In addition to initialize and initialize_cpoy way, they will always be private methods.
 protection method (Protected Method)
 method can only be defined in this way the object of the class itself and subclasses of this class object access.
 private methods (private Method)
 method can only be defined in this way the object of his visit to the class, even other objects of this class can not access.

Ruby of protection methods and private methods and general object-oriented programming languages have different concepts, the protection method means that we can only approach this method can only be defined object classes and their subclasses object access, private methods access can only be the object itself.

class Test
def method1 # default is public way ...
end

protected # protected method
def method2
...
end

private # private methods
def method3
end

public
def test_protected (arg) # arg is the object of class Test
arg.method2 # correctly, you can access the same way other objects of protection
end

def test_private (arg) # arg is the object of class Test
arg.method3 # error, can not access private methods other objects of similar
end
end

obj1 = Test.new
obj2 = Test.new

obj1.test_protected (obj2)
obj1.test_private (obj2)

Can be seen, and C + + / Java comparison, Ruby provides better encapsulation.

You can also use the following simpler form:
class Test
def method1
...
end

def method2
...
end

def method3
...
end

def methdo4
...
end

public: method1
protected: method2
private: method3,: method4
end

Ruby and C + + / Java is a notable difference is the runtime access control decisions, rather than static binding. So only in a restricted access method will generate run-time error.

§ 3.6 metaclasses are objects in Ruby, everything. Class and instance objects are objects. It sounds a bit hard to pronounce, let's look at an example:
class Person
def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
end
end
a = Person.new ('Tom', 'male', 15)

puts a.object_id => 22429840
puts Person.object_id => 22429960

Yes, classes are objects, this is Ruby and C + + / Java in a significantly different in C + + / Java, the class is just a data abstraction, and not also the object of such a concept class. In Ruby, the concept of the existence of metaclasses, classes are objects, all classes are instances of objects per class. And C + + / Java comparison, Ruby object-oriented higher degree.
Can see objects as class objects and instances have their own ojbect_id, you can call an instance of the object as the same way as to use it to call class methods. All class object class is Class class, Oject class is the base class for all classes.
irb (main): 003:0> Object.class
=> Class
irb (main): 004:0> Object.superclass
=> Nil

In this way, we can understand the class from another angle variables and class methods, class variables is the object of a class instance variables, class methods of a class object class refers to the special method.
Specific class methods can be divided into two types: first is the parent of all classes defined in class Class, and shared by all the class methods; the second is unique to each class of special methods.
Class method of self refers to the class itself, and that needs to keep in mind, so that we can define class methods use a variety of ways.

class Test
# Define class method mode 1
def Test.meth1
# ...
end

# Define class method mode 2
def self.meth2
# ...
end

# Define class method mode 3
class <<Test
def meth3
# ...
end
end

# Define class method mode 4
class <<self
def meth4
# ...
end
end
end

§ 3.7 Ruby's dynamic nature can be re-defined the same way
class RedefTest
def meth
puts "This is meth"
end
end

obj1 = RedefTest.new
obj1.meth

class RedefTest
def meth
puts "This is new meth"
end
end

obj1.meth

Implementation of the results:
This is meth
This is new meth

You can use undef_method cancel a method definition

class UndefTest
def meth
puts "This is meth"
end
end

obj1 = UndefTest.new
obj1.meth

class UndefTest
undef_method (: meth)
end

obj1.meth

Implementation of the results:
This is meth
test.rb: 14: undefined method `meth 'for # <UndefTest:0x2ac8240> (NoMethodError)

§ 3.8 Variable variable name length limited only by memory size. Ruby can distinguish the first character variable name to distinguish it is the local variables, instance variables, class variables, global variables or constants. Typically, the variable name after the second character is a number, letter or underscore, but some internal variable names are special, such as "$?"。

§ 3.8.1 Local variables local variables in lower case letter or underscore.

num = 1
foo

The scope of local variables in the statement of Department beginning, the end of the block is located in the declaration, method definition, class / module definition to the end.

2.times (
p defined? (num)
num = 10
p num
)

Output:
nil
10
nil
10

Even if the statement is not part of the implementation of the interpreter is still effective because the treatment has been the interpreter.

v = 1 if false
p defined? (v)
pv

Output:
"Local-variable"
nil

However, if the block has become a process object, then the local variable will continue until the end of the process until the object. If the number of process object reference with a scope, then the local variable will be shared by these objects.
(To-do example)

§ 3.8.2 instance variables begin with @ variable is an instance variable, instance variable belonging to a particular object.
class Person
def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
end
end

The example above, @ name, @ gender, @ age are instance variables. In class or child class method references instance variables. If the reference has not been initialized the instance variable, then its value is nil.

§ 3.8.3 Class variables start with @ @ variable is the class variable. Class variables defined in the class definition, you can kind of special method, instance method, etc. of the class of variable references and assignments. Class variables are class, subclass, and their shared instance of an object.
class Person
@ @ Number = 0 # initial value before use must be
def initialize (name, gender, age)
@ Name = name
@ Gender = gender
@ Age = age
@ @ Number + = 1
end
end

Class variables are private, outside the class can not directly access, you can only instance methods and class methods to access it. Class variables can be viewed as a class, subclass, and their shared instance of global variables.
Class variables defined in the module (module variables) are all included in the modules shared by the class.
module TestModule
@ @ Foo = 10
end
class Klass
include Foo
p @ @ foo + = 1 # => 11
end
class Base
include Foo
p @ @ foo + = 2 # => 12
end

§ 3.8.4 global variables $ start variable is global variables, global variables can be referenced anywhere in the program. Global variables without variable declarations. Reference not initialized global variable, its value is nil.
Ruby runtime environment, a series of predefined global variables, the pre-defined global variables, see Table.

§ 3.8.5 constant constant initial capital letters, constant definitions and initialization process is completed by the assignment.
PI = 3.14
E = 2.71
If the definition of the constants that have been assigned, then a warning message appears. If the reference to undefined constant trigger NameError exception.
PI = 3.14
obj1 = 2 * PI * 10
PI = 3.1415 # warning: already initialized constant PI
obj2 = Foo # uninitialized constant Foo (NameError)

Constants can be defined in classes and modules can not be defined in the method.

class Meth
PI = 3.14 # OK
end

def circle_area (arg)
PI = 3.14 # ERROR
PI * arg * arg
end

If you want to visit a class or in an external constant module, you should use the "::" operator.

class Meth
PI = 3.14
end

def circle_area (arg)
Math:: PI * arg * arg
end

Expressions generated in the class definition, while the class object, but also the class object assigned to a class of the same name with the constant reference to the class name that is referenced to the constant.
class Test
end

p Test.class # Class
p Test # test

To visit the Object class constants (top-level constant), they need to also use the "::" operator, but the operator on the left is empty.

§ 3.8 and the definition of the operation of § 3.8.1 alias
Alias keyword to add the alias method or global variables. Can specify an identifier to the method name as an alias or Symbol. A method to add an alias, the alias method and original method of binding at the moment, since even if the re-definition of the original method, the alias method remains focused on pre-defined characteristics of the old method. If the change in a certain way of content, want to use the method before the amendment, the alias will be useful. You can also use Module # alias_method to the method to add an alias.
# Define meth method
def meth
puts "This is meth"
end

# Set alias
aliasrig_meth: meth

# Re-define foo
def meth
puts "This is new meth"
end

p meth

Implementation of the results:
This is new meth
nil

Alias to the global variable settings mean that the two names point to the same global variable. When you assign to one, the other will be changed.

$ Abc = 1
alias $ xyz $ abc
$ Xyz = 2
p [$ abc, $ xyz] # => [2, 2]

But not to the regular expressions in the variables $ 1, $ 2, and so add an alias, In addition, some global variables is important for the interpreter, if the re-definition of their words, sometimes affect the normal work of the interpreter.

§ 3.8.2 undef
undef a method used to cancel the definition, you can also use the cancellation method Module # undef_method method definition. undef will delete the method name and definition of the relationship between methods, even with the same name in the superclass method call will raise an exception.

class Base
def meth
puts "This is Base # meth"
end
end

class Derived <Base
def meth
puts "This is Derived # meth"
end
end

class Test1 <Derived
def meth
puts "This is Test1 # meth"
end

undef_method (: meth)
end

obj1 = Test1.new
obj1.meth

Implementation of the results:
Tes1.rb: 22: undefined method `meth 'for # <Test1:0x2ac7c88> (NoMethodError)

The Module # remove_method method only way for abolition of the current class and method names defined the relationship between the parent class method can call the same name, this difference is very important.
class Base
def meth
puts "This is Base # meth"
end
end

class Derived <Base
def meth
puts "This is Derived # meth"
end
end

class Test2 <Derived
def meth
puts "This is Test2 # meth"
end

remove_method (: meth)
end

obj2 = Test2.new
obj2.meth

Implementation of the results:
This is Derived # meth

Add the alias using alias cancellation or undef definition will modify the class interface, without restrictions on the parent class. Inheritance and Mix-in's functions are to add the class methods, and undef can cancel method. However, if necessary cancel the class method (method calls by other means), then the consequences would be disastrous.

§ 3.8.3 defined?
Defined? Used to determine whether the definition of the expression. If the expression is not defined, it returns nil, if it has been defined, it returns a string describing the type of the expression.

defined? Val # => nil
defined? true # => "true"
defined? $ * # => "global-variable"
defined? Array # => "constant"
defined? Math:: PI # => "constant"
defined? num = 0 # => "assignment"
defined? 100 # => "expression"
defined? 100.times # => "method"

Although defined? Looks like a method, actually the operator Ruby syntax, it will not be calculated parameters. Therefore, the following expression does not output "abc".
defined? print ("abc \ n")

If the method is not defined, or ways to use undef or Module # remove_method canceled the original definition, defined? Will return nil.
Note If a method with a capital letter at the beginning, use defined? Determine when the method name with "()" when, or method name will be as constant handling.
def Foo (arg)
end

p defined? Foo # => nil
p defined? Foo () # => "method"

Foo = 1
p defined? Foo # => "constant"

You can also use the following special use:

 determine whether the available yield
defined? yield
If the yield call is available, return true, the specific return value is the string "yield". Its role with block_given?, As can be judged whether to block the way with a method call.
class Base
def foo
puts defined? yield
end
end

a = Base.new
a.foo
a.foo ()

Implementation of the results:
nil
yield

 determine whether the available super
defined? super
If the super can be called, it returns true, the specific return value is the string "super".

class Base
def foo
end
end

class Derived <Base
def foo
puts defined? super
end

def fun
puts defined? super
end
end

obj = Derived.new
obj.foo
obj.fun

Implementation of the results:
super
nil

 returned no assignment, but has defined local variables.

defined? a = 1 # => assignment
pa # => nil

 use in regular expressions
/(.)/ = ~ "Foo"
p defined? $ & # => "$ &"
p defined? $ 1 # => "$ 1"
p defined? $ 2 # => nil

Chapter Four basic types of § 4.1 Array
Array, also known as the array is an ordered collection of a series of elements. You can explicitly use the Array class methods to create a new array of objects, you can also use a number surrounded by square brackets, comma-separated numeric or string form an array.

irb (main): 007:0> a = ["first" "second" "third"]
=> ["Firstsecondthird"]
irb (main): 008:0> a = ["first", "second", "third"]
=> ["First", "second", "third"]
irb (main): 009:0> a.class
=> Array
irb (main): 010:0> a.length
=> 3
irb (main): 011:0> a [0]
=> "First"
irb (main): 012:0> a [1]
=> "Second"
irb (main): 013:0> a [2]
=> "Third"
irb (main): 014:0> a [3]
=> Nil
irb (main): 015:0> b = Array.new
=> []
irb (main): 016:0> b.class
=> Array
irb (main): 017:0> b.length
=> 0
irb (main): 018:0> b [0] = "first"
=> "First"
irb (main): 019:0> b [1] = "second"
=> "Second"
irb (main): 020:0> b
=> ["First", "second"]

Array can use [] to the index, in fact [] is a method of Array class, it can even quilt cover type (overridden). Ruby, the more interesting is the array index of a variety of ways, you can use negative numbers to index the array. That start from the rear negative, such as index -1 is the last element, the index is -2 expressed by the second element, and so on.

irb (main): 021:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb (main): 022:0> a [-1]
=> 5
irb (main): 023:0> a [-2]
=> 4
irb (main): 024:0> a [-9]
=> Nil

You can also use a pair of numbers to index the array, the first number that the starting position, the second number indicates position from the beginning since the number of elements.

irb (main): 025:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb (main): 026:0> a [1, 3]
=> [2, 3, 4]
irb (main): 027:0> a [3, 1]
=> [4]
irb (main): 028:0> a [-3, 1]
=> [3]

You can even use a scope to index array that contains the tail elements .., ... that does not contain the tail elements.

irb (main): 029:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb (main): 030:0> a [1 .. 3]
=> [2, 3, 4]
irb (main): 031:0> a [1 ... 3]
=> [2, 3]

§ 4.2 Hash
Hash also known as hash tables hash table, similar to the array, but each element has an index, sometimes called an associative array, hash array or dictionary. Hash table and array of different arrays can only use the numeric index, while the hash table, you can use any object index. Hash table and array of other notable difference is that the hash table elements are disordered. Each hash table in the Ruby Hash class is an object.
In the hash table, we call the index for the Key, index of element to be known as the Value.
We can use => to connect the elements to create a hash table, attention is to use hash table outside surrounded by braces.

irb (main): 032:0> h = ("first" => "Amy", "second" => "Mike", "third" => "Tom")
=> ("Third" => "Tom", "second" => "Mike", "first" => "Amy")
irb (main): 033:0> h.length
=> 3
irb (main): 034:0> h ["first"]
=> "Amy"
irb (main): 035:0> h ['second']
=> "Mike"
irb (main): 036:0> h [100] = "Henry"
=> "Henry"
irb (main): 037:0> h ["nine"] = "Rose"
=> "Rose"
irb (main): 038:0> h
=> ("Third" => "Tom", "second" => "Mike", 100 => "Henry", "first" => "Amy", "nine" => "Rose")

§ 4.3 Number
Ruby support for integer types and floating-point type. Integer can be any length (the length and memory size of only). In a certain range of the integer is considered Fixnum class object. Beyond the scope of the integer is considered Bignum class object.

num = 81

6.times do
puts "# (num.class): # (num)"
num *= num
end

Run Results:
Fixnum: 81
Fixnum: 6561
Fixnum: 43046721
Bignum: 1853020188851841
Bignum: 3433683820292512484657849089281
Bignum: 11790184577738583171520872861412518665678211592275841109096961

And C / C + + the same, Ruby provides a number beginning with 0 as octal numbers, beginning with 0x hexadecimal number to 0b binary number beginning.

irb (main): 001:0> 16
=> 16
irb (main): 002:0> 020
=> 16
irb (main): 003:0> 0x10
=> 16
irb (main): 004:0> 0b10000
=> 16

A number of intermediate connections can underline, underscore automatically be ignored.

irb (main): 005:0> 123_456_789
=> 123456789

You can use "? \ Cx" or "? \ Cx" control characters generated.

If a number contains a decimal point or contain "e", then the number will be converted to Float class object.

irb (main): 012:0> 1.0.class
=> Float
irb (main): 013:0> 1.0e3.class
=> Float
§ 4.4 String
String, also known as string is surrounded by single quotes or double quotes the string of characters up. Single and double quotes have different meaning, double-quoted character for variable substitution, surrounded by single quotation marks do not do variable replacement. Can be used in the string # (expr) embed code.

irb (main): 022:0> "The seconds in a day is: # (24 * 60 * 60)"
=> "The seconds in a day is: 86400"
irb (main): 023:0> 'The seconds in a day is: # (24 * 60 * 60)'
=> "The seconds in a day is: \ # (24 * 60 * 60)"

You can also use% q and% Q to generate a string object. % Q is equivalent to single quotes,% Q is equivalent to double quotation marks.

irb (main): 051:0>% q / Single quote /
=> "Single quote"
irb (main): 052:0>% Q / Double quote /
=> "Double quote"
irb (main): 053:0>% q / # (50 * 50) /
=> "\ # (50 * 50)"
irb (main): 054:0>% Q / # (50 * 50) /
=> "2500"

% Q and% Q for the first character behind the separator. Separator character between the brother was considered a string. However, if the separator is [(<, then the end of the mark for the match])>.

irb (main): 055:0>% q (This is a string)
=> "This is a string"
irb (main): 056:0>% Q [This is a string]
=> "This is a string"
irb (main): 057:0>% q <This is a string>
=> "This is a string"

You can also use the "Here Document" means to generate a string, this method provides <<after the end of the string as a symbol.
string = <<END_OF_STRING
With publication started in June 1948 and a current circulation of 3 million,
People's Daily is the most influential and authoritative newspaper in China.
According to UNESCO, it takes its place among the world top 10.
END_OF_STRING

To note that at the end of the END_OF_STRING must be placed in the first row.
§ 4.5 Range
Range, also known as the scope is used to indicate a continuous sequence of values. You can use ... .. and operators to produce Range, said the former contains the last element, the latter said they did not contain the last element. Range object belongs to class is the Range. Note Range and Array are different, you can use the Range class to_a way into a Range object Array object.

irb (main): 003:0> (1 .. 10). to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb (main): 004:0> ('bar' .. 'bat'). to_a
=> ["Bar", "bas", "bat"]
irb (main): 005:0> (1 ... 10). to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Range in addition to a sequence that can appear in conditions outside the statement. In the conditional statement, you can switch the Range as a two-way, when the first condition is satisfied when the switch, the second condition is satisfied when the off switch.
a = [0, 1, 2, 3, 4, 5, 6]
a.each do | i |
print i, "" if i == 1 .. i == 5
end

Implementation of the results
12345

The code if i == 1 .. i == 5 means that only meet i == 1 i == 5 and does not meet the conditional is true if not satisfied i == 1 or i == 5 at the right time to meet the false intuitively see that the scope of that element needs to be located among the.

You can use === to test whether an element in a range:

irb (main): 093:0> (1 .. 10) === 3
=> True
irb (main): 094:0> (1 .. 10) === 30
=> False
irb (main): 095:0> (1 .. 10) === 2.71828
=> True
irb (main): 096:0> ('a' .. 'f') == 'c'
=> False
irb (main): 097:0> ('a' .. 'f') == 'g'
=> False

Range can also be located within the case statement:

score = 98
case score
when 85 .. 100 then puts "A"
when 70 ... 85 then puts "B"
when 60 ... 70 then puts "C"
else puts "D"
end

Implementation of the results:
A
§ 4.6 Symbol
Symbol is a simple object, it uses the name as a unique identifier. Interpreter Symbol object represents a unique internal name. Symbol generation is very simple, just give a character sequence, add ":" or "to_sym" method. Symbol Symbol subordinate object class.
String and Symbol both of which have close ties. Each symbol has a string name (can be obtained using the to_s). String can request each of its corresponding symbol (by to_sym method). String and Symbol are closely related, but they are not the same thing, they were String objects class and the Symbol class.
Readers may ask, why does there Symbol object? Because the symbol can greatly improve the speed. Symbol's internal representation is an integer, Hash table used for keyword search string, while the Ruby language parser implementation, computing device requires a lot of class names, method names in the search, which can greatly speed up the analysis and implementation Find the speed of the string.
Think, without Symbol, if needed method name as a parameter, we have used that method to a string name, interpreter for processing first string parsing, and then to find out the appropriate way, and if Symbol will use to speed up the pace considerably.
In use, Symbol is often said that a name, such as a variable foo has the value 1, then: foo can be interpreted as variable names, if the direct reference to foo, will be one, but if it is: foo to refer to the variable name itself.

Symbol object is unique. Every time you use the code: test, you want to reference a name for the "test" of the Symbol class of objects. Ruby ensure that the system has only one name for the test of Symbol objects, all right: test of the references to reference the same object.

irb (main): 001:0> module One
irb (main): 002:1> class Test
irb (main): 003:2> end
irb (main): 004:1> $ f1 =: Test
irb (main): 005:1> end
=>: Test
irb (main): 006:0> module Two
irb (main): 007:1> Test = 1
irb (main): 008:1> $ f2 =: Test
irb (main): 009:1> end
=>: Test
irb (main): 010:0> def Test ()
irb (main): 011:1> end
=> Nil
irb (main): 012:0> $ f3 =: Test
=>: Test
irb (main): 013:0> $ 1.object_id
=> 4
irb (main): 014:0> $ 2.object_id
=> 4
irb (main): 015:0> $ 3.object_id
=> 4

§ 4.7 regular expression regular expression class is Regexp, you can use / or% r generate regular expressions.

irb (main): 103:0> a = / \ s * [af] /
=> / \ S * [af] /
irb (main): 104:0> a.class
=> Regexp
irb (main): 105:0> b =% r (\ s * [af])
=> / \ S * [af] /
irb (main): 106:0> b.class
=> Regexp
irb (main): 107:0> c = Regexp.new ('\ s * [af]')
=> / \ S * [af] /
irb (main): 108:0> c.class
=> Regexp

You can use the Regexp # match (string) method or the = ~ operator to match the regular expression, you can use! ~ To test whether the mismatch.

irb (main): 113:0> sentence = "This is a dog."
=> "This is a dog."
irb (main): 114:0> sentence = ~ / dog /
=> 10
irb (main): 115:0> sentence = ~ / a /
=> 8
irb (main): 116:0> / o / = ~ sentence
=> 11
irb (main): 117:0> sentence! ~ / xyz /
=> True

In addition, matching the regular expression, the string will be matched to a variable stored in $ &, $ 'variable in the store already had the character sequence match, $ `variable not match the stored sequence of characters.

irb (main): 118:0> sentence = "This is a dog."
=> "This is a dog."
irb (main): 119:0> sentence = ~ / a /
=> 8
irb (main): 120:0> puts $ &
a
=> Nil
irb (main): 121:0> puts $ '
dog.
=> Nil
irb (main): 122:0> puts $ `
This is
=> Nil

Chapter V code blocks and iterators § 5.1 block (Block)
§ 5.1.1 What is the code block in Ruby in the code between the curly braces or on the do / end code between a code block. Block can only be behind in a way that it immediately in the way the last argument of the same line. The content block will not be immediately implemented, while implementation of the method to be called when the interpreter's run-time environment will remember the scene block appears, and then perform the called method.

[1,2,3,4,5]. Each (| i |
puts i
)

[1,2,3,4,5]. Each do | i |
puts i
end

General usage is: (to-do detailed explanation)
 When the interest margin (side effect) effects of the use of do / end.
 When the results return to seasonal use care braces.

§ 5.1.2 code block with the object code block is not the object, but can be easily transformed into an object class Proc. There are three methods of transformation:
 a block of code passed to the last parameter to & start method.
def meth1 (p1, p2, & block)
puts block.inspect
puts block.call
end
meth1 (1, 2) ("This is a block")

 Use Proc.new method, the parameters behind a block of code:
block = Proc.new ("a block")

 call Kernel.lambda methods:
block = lambda ("a block")

The first two methods are equivalent, while the third method, using lambda and use the resulting Proc objects Proc objects Proc.new generated there is a difference. This is a subtle difference, the difference associated with the return keyword. The return lambda from lambda return. The Proc of return method to return from the periphery.
Can see two examples:
def test_proc
p = Proc.new (return 1)
p.call
puts "Never come here"
end

test_proc # => 1

After the implementation of "Never come here" will not be output, the implementation of p.call equivalent method in the implementation of the return test_proc statement.

def test_lambda
p = lambda (return 1)
result = p.call
puts "The value is: # (result)"
end

test_lambda

After the implementation of the results:
The value is: 1

Shows the resulting Proc objects using lambda implementation of call when the method call, return that block from the lambda or surrounded by return.

In a block implementation of the next statement causes the block to return. After the return value is the next statement with the parameters. If the next does not have any parameters, then the return value is nil.

def meth2
result = yield
"The block result is # (result)"
end

puts meth2 (next 9)

pr = Proc.new (next 100)
puts pr.call

pr = lambda (next)
puts pr.call

Implementation of the results:
The block result is 9
100
nil
§ 5.2 iterators (Iterator)
§ 5.2.1 What is the iterator simply speaking, an iterator is a method acceptable to block. Had to operate and set up the iterative method with a block, so now it is still often referred to as Diego with a device.

[1,2,3,4,5]. Each (| i |
puts i
)
The code, each method of repeatedly calling code block, we call each method is an iterator.

Iterators (Iterator) i.e. method call with a block. In fact, in earlier versions of Ruby, the use of the code block is called an iterator, because they are designed to achieve loop iteration. But in Ruby development, the use of block later have been greatly enhanced, from the initial cycle of abstraction to anything. Who can be called the iterative method of operation of the iterator, but if all method calls with blocks of iterative process are seen as devices, then the concept is not suitable and will cause confusion § 5.2.2 using the iterator
# A simple example of using iterators, array element as a parameter for each subsequent block of code execution
['This', 'is', 'a', 'dog']. Each do | entry |
print entry, ''
end

Implementation of the results:
This is a dog

# Another example of using the iterator, block access to its external data
factorial = 1
1.upto (10) do | i |
factorial *= i
end
puts factorial
Implementation of the results:
3628800

# Code block, the return value can be called to use
b = [1, 2, 3, 4, 5]. map do | entry |
entry * entry
end
print b.inspect

Implementation of the results:
[1, 4, 9, 16, 25]

# Code block you can use more than one parameter
result = (0 .. 100). inject (0) do | sum, i |
sum + i
end
print result

Implementation of the results:
5050

§ 5.2.3 yield
Yield in the method can be used to execute code block content, just as the incoming block of code is the same as part of this approach. Whenever get a yield call, the contents of the code block will be executed once. When the code block executes after the end of the program will yield back to the line continues.

def twoTimes
yield
yield
end
twoTimes (puts "Hello World!")

Implementation of the results:
Hello World!
Hello World!

You can pass parameters using the yield operation to a block of code, and retrieve the return value from a code block.

def fibonacii (max)
f1, f2 = 1, 1
while f1 <= max
yield f1
f1, f2 = f2, f1 + f2
end
end

fibonacii (1000) (| f | print f, "")

Implementation of the results:
1,123,581,321,345,589,144 233 377 610 987

In this case, yield to receive a parameter, this parameter will be executed when the block passed to the specified. In the code block, the receiver parameters enclosed with two vertical lines on the head block. operation can yield a return value, yield the return value of operation is the last block of code value of the expression.

§ 5.2.4 to write your own iterator
def factorial (count, & block)
value = 1
1.upto (count) do | i |
value = value * i
block.call (i, value)
end
end

factorial (5) do | i, sum |
puts "factorial (# (i)) = # (sum)"
end

Implementation of the results:
factorial (1) = 1
factorial (2) = 2
factorial (3) = 6
factorial (4) = 24
factorial (5) = 120

You can also save incoming block of code for later use:
class Mathematics
def initialize (& block)
@ Block = block
end

def factorial (max)
value = 1
1.upto (max) do | i |
value = value * i
@ Block.call (value)
end
end
end

the_value = Mathematics.new do | count |
puts "Current value is # (count)"
end

the_value.factorial (5)

Implementation of the results:
Current value is 1
Current value is 2
Current value is 6
Current value is 24
Current value is 120

Chapter VI expression
Ruby has a return value of all languages, this is Ruby language and other programming languages a significant difference.
irb (main): 006:0> a = b = c = 0
=> 0
irb (main): 007:0> print "\ n"

=> Nil
Similarly, if and case statements also return values, if and case statements and if the return value is the last case the value of an executive statement.
irb (main): 014:0> if (1 +1 == 2)
irb (main): 015:1> "Like in school."
irb (main): 016:1> else
irb (main): 017:1 * "What a surprise!"
irb (main): 018:1> end
=> "Like in school."

§ 6.1 operators, like other programming languages, Ruby is rich in operators. But in Ruby, most operators are actually method calls. For example, a + b, in fact the true running a. + (b), the object of the + method of calling a, b as the parameters of this method. This has brought considerable flexibility, you can change the semantics of the original operator to give it new meaning.

Just as an example the following code to rewrite the Fixnum class + method, given two fixed-length integer add new meaning.
irb (main): 001:0> class Fixnum
irb (main): 002:1> alias the_plus +
irb (main): 003:1 * def + (integer)
irb (main): 004:2> the_plus (integer) * 2
irb (main): 005:2> end
irb (main): 006:1> end
=> Nil
irb (main): 007:0> 1 +1
=> 4
irb (main): 032:0> 2 +2
=> 8
irb (main): 132:0> 2 +5
=> 14

For the operators (+ - * /% ** & | ^ <<>> & & | |), Ruby has the appropriate form of abbreviated assignment operator + =, -= and so on.

Operator precedence:
::
[]
+ (Unary) - (one dollar)! ~
* /%
+ -
<<>>
&
| ^
>> = <<=
<=> == ===! = = ~! ~
& &
| |
.. ...
?:
= + = -= *= / = (Assignment operator of all abbreviations)
not
and or

The following operators can not serve as a method call, that can not change the meaning of the following operators:
...
!
not
& &
And
| |
Or
::
=
+ = -= *= / = (Assignment operator of all abbreviations)
?:

§ 6.2 command substitution in the Shell, you can use anti-quotation marks (`) implementation of the command substitution.
`Date` => Mon Nov 27 11:07:22 CST 2006
`Pwd` => / usr / include

Ruby also has this feature. In Ruby, you can use anti-quotation marks or% x to perform command substitution. Command substitution expression returns the value of the output is the command. The return value of command is stored in the global variable $? In.
irb (main): 2134:0>% x (echo "Hello World!")
=> "\" Hello World! \ "\ N"

The default behavior is anti-quotation marks the implementation of command substitution, and similarly, we can rewrite it, give it new meaning.
alias old_backquote `
def `(cmd)
result = old_backquote (cmd)
if $?! = 0
fail "Command # (cmd) failed: # $?"
else
puts "Command # (cmd) success."
end
result
end
print `date`
print `data`

Implementation of the results:
Command date success.
Mon Jan 15 21:48:16 CST 2007
Command uname success.
Linux

§ 6.3 Assignment Operators
to-do defined.

Assignment operator return value is the value of value left, so can chain assignment.
irb (main): 001:0> a = b = c = 5
=> 5
irb (main): 002:0> a = (b = 1 + 2) + 5
=> 8

Ruby's basic assignment in two forms, one on the left is an object or variable, then the right value or variable reference given to the left. This assignment operator provided by the language itself.
irb (main): 003:0> str = "This is a dog."
=> "This is a dog."
irb (main): 004:0> num = 100
=> 100
Another form of assignment operator on the left is an instance of the class of a property, this often means the implementation of this class, method name "attribute =." The return value is the value of the right value, you can override this method to give it new meaning.

irb (main): 001:0> class Test
irb (main): 002:1> def num = (num)
irb (main): 003:2> @ num = num
irb (main): 004:2> end
irb (main): 005:1> end
=> Nil
irb (main): 006:0> t = Test.new
=> # <Test:0x2e20568>
irb (main): 007:0> t.num = 10
=> 10

§ 6.4 Parallel Assignment
Another interesting Ruby supports parallel assignment. For example, the exchange of two variables a, b's value can be written as:
a, b = b, a
Ruby would be calculated first from left to right = right of expression, and then perform the action assigned.
irb (main): 008:0> x = 0
=> 0
irb (main): 009:0> a, b, c = x, x + = 1, x + = 2
=> [0, 1, 3]

If the left than the right side of the multi-variable, then the extra variables will be assigned to nil.
irb (main): 001:0> x, y, z = 1, 2
=> [1, 2]
irb (main): 002:0> print z
nil => nil

If the right of the variable or value more than the left, then the excess will be ignored.
irb (main): 001:0> x, y = 1, 2, 3 # 3 will be ignored
=> [1, 2, 3]

Assignment can also be used in parallel array assignment.
irb (main): 001:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb (main): 002:0> x, y = a
=> [1, 2, 3, 4, 5]
irb (main): 003:0> puts x, y
1
2
=> Nil

Assignment in the parallel array can be used * * appear in the left side of the last variable, said the array of all the remaining value is assigned to the variable.

irb (main): 001:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb (main): 002:0> x, * y = a
=> [1, 2, 3, 4, 5]
irb (main): 003:0> puts x
1
=> Nil
irb (main): 004:0> puts y
2
3
4
5
=> Nil

* Appear on the right side of the last variable, and left similar.
a = [1, 2, 3, 4]
b, c = 9, a => b == 9, c == [1, 2, 3, 4]
b, c = 9, * a => b == 9, c == 1
b, * c = 9, a => b == 9, c == [[1, 2, 3, 4]]
b, * c = 9, * a => b == 9, c == [1, 2, 3, 4]

§ 6.5 nested assignment in the assignment, the left side of the variables you can use the brackets. This variable is in brackets as in a level.
b, (c, d), e = 1,2,3,4 => b == 1, c == 2, d == nil, e == 3
b, (c, d), e = [1,2,3,4] => b == 1, c == 2, d == nil, e == 3
b, (c, d), e = 1, [2,3], 4 => b == 1, c == 2, d == 3, e == 4
b, (c, d), e = 1, [2,3,4], 5 => b == 1, c == 2, d == 3, e == 5
b, (c, * d), e = 1, [2,3,4], 5 => b == 1, c == 2, d == [3, 4], e == 5

§ 6.6 Other assignment
Ruby support from the plus (+ =) and decrement operators. And C / C + + / Java, like, a = a + 2 can be written as a + = 2. There are other similar operator% = ~ = / = = + = | = & =>> = <<= *= & & = | | = **=.
We often encounter statements like these words [key] | | = [], his words [key] = words [key] | | [] equivalent, meaning that if the Hash table words [key] value is empty When, on the words [key] assignment to a new empty array, otherwise unchanged.
Accordingly, for
num = 1 if num.nil?
num = 1 unless num
Ruby in the habit of writing to num | | = 1, so the code more concise.
§ 6.7 Conditional operators Boolean operators are defined in Ruby nil and false is false, the other value is true. Attention, and the C / C + + The difference is that 0 is not to be construed as false, empty string is the same.
Ruby supports common Boolean operators, such as and and & &, but also introduce a new Boolean operators' defined? '.

Like other programming languages, and and & & on behalf of and relationships.
or and | | on behalf of or relationship.
Not and! Representatives of non-relationship.

If the parameter is not defined defined? Return nil, otherwise return a description string used to describe the parameter information.
irb (main): 013:0> defined? 1
=> "Expression"
irb (main): 014:0> defined? dummy
=> Nil
irb (main): 015:0> defined? printf
=> "Method"
irb (main): 016:0> defined? String
=> "Constant"
irb (main): 017:0> defined? $ _
=> "Global-variable"
irb (main): 018:0> defined? Math:: PI
=> "Constant"
irb (main): 019:0> defined? a = 0
=> "Assignment"
irb (main): 020:0> defined? 30.abs
=> "Method"

Conditional operator
Ruby supports a conditional operator, ==, ===, <=>,=~, eql?, Etc., equal?. Except "=> others are class methods. == And = ~ a negative form! = And! ~.

If and unless
Ruby in the if and the other programming languages if similar:
if x == 5 then
print "The value of x is 5."
elsif x == 0 then
print "The value of x is 0."
else
print "The value of x is", x
end

Can be omitted then:
if x == 5
print "The value of x is 5."
elsif x == 0
print "The value of x is 0."
else
print "The value of x is", x
end

If the compact and the code to the code on the same line are not omitted, then:
if x == 5 then print "The value of x is 5."
elsif x == 0 then print "The value of x is 0."
else print "The value of x is", x
end

You can also use a colon-separated, so the code more compact:
if x == 5: print "The value of x is 5."
elsif x == 0: print "The value of x is 0."
else print "The value of x is", x
end

As we said before, if is an expression, it has its own return value. You can ignore the return value, but he does exist. If the return value statement is the value of the last executed statement.
x = 10
str = if x == 5: "x == 5"
elsif x == 0: "x == 0"
else "x ==?"
end
After the implementation of the contents of str is: x ==?

Ruby also supports if the negative form unless, unless the syntax and if there is no difference.
unless x! = 5
print "The value of x is 5."
else
print "The value of x is not 5."
end

Ruby also supports C / C + + for?: Operator.
str = x == 5? "x == 5": "x ==?"

Ruby inherited from a very good Perl syntax, you can write the conditions behind the expression.
puts "a = # (a)" if debug
print total unless total.zero?

§ 6.8 case expression
Ruby's case statement is very strong, we first look at a basic usage:
grade = case
when point> = 85: 'A'
when point> = 70 & & point <80: 'B'
when point> = 60 & & point <70: 'C'
when point <60: 'D'
else 'E'
end
Here the role of case statements and if an expression similar, case statement, the return value is the final implementation of the value of the expression. And if a similar statement, if the words written on the same line were required to then or colon.

Another is the most common form of the case out after the goal and objectives and then compare each statement in turn:
case input_line
when "debug"
print "We are in debug mode."
when / p \ s + (\ w +) /
dump_variable ($ 1)
when "quit", "exit"
exit
else
print "Illegal command: # (input_line)"
end

Another example:
Season = case month
when 3 .. 5: "Spring"
when 6 .. 8: "Summer"
when 9 .. 11: "Autumn"
when 12 .. 2: "Winter"
else "Error"
end

Ruby provides an operator ===, === as long as a class provides methods that this class of objects can appear in the case statement. For example, for regular expression pattern matching as defined ===.

Ruby, all classes of the base class is the Class class, all classes are instances of Class instance of the class (to-do). It defines the meaning of === is provided for the parameters whether the instance of the class or parent class.
case shape
when Square, Rectangle
# ...
when Circle
# ...
when Triangle
# ...
else
# ...
end

§ 6.9 § 6.9.1 Loop Cycle
Loop cycle was always the implementation of the method blocks until the break out.
x = 0
loop do
x + = 1
if x <= 5: print x, ""
else break
end
end
Implementation of the results: 1 2 3 4 5.
§ 6.9.2 While
When the condition is true While loop to continue, exit the loop when the condition is false.
x = 0
while x <10
x + = 1
end

§ 6.9.3 Until
Until and While rooms when the condition is false While loop to continue, exit the loop when the condition is true.
x = 0
until x == 9
x + = 1
end

§ 6.9.4 Iterator
And C / C + + / Java different, Ruby language does not support C / C + + / Java in the For loop, but Ruby through the iterator to provide more powerful features. Look at an example:
4.times do
puts "Hello!"
end
Implementation of the results:
Hello!
Hello!
Hello!
Hello!
In addition to times methods, integer offer upto and downto the two methods, see the following example,
0.upto (9) do | i |
print i, ""
end
Implementation of the results of 0123456789.

You can also use Step method, step step, said second parameter:
0.step (10, 2) do | i |
print i, ""
end
Implementation of the results is: 0246810.

Many container classes, such as arrays, each method in turn provides the data traversing the container:
[1, 2, 3, 4, 5]. Each (| i | print i, "")
Implementation of the results: 1 2 3 4 5.

If a class to support each method, then you can use some of the methods in Enumerable module.
["Apple", "orange", "banana", "watermelon"]. Grep (/ an /) do | fruit |
puts fruit
end
Implementation of the results:
orange
banana

§ 6.9.5 For .. In
If a class provides each method, then the corresponding, this class of objects you can use For .. in loop. For example, Range Array class and each class has a method:
for fruit in ["apple", "orange", "banana", "watermelon"]
print fruit, ""
end
Implementation of the results: apple orange banana watermelon.
for i in 1 .. 9
print i, ""
end
Implementation of the results: 123,456,789.

§ 6.9.6 Break, Redo, Next
Break, Redo, and Next to change the cycle process.

§ 6.9.6.1 break
Break to exit the current loop:

times = 0
loop do
times + = 1
print "hello # (times) \ n"
break if times> 2
end

Implementation of the results:
hello 1
hello 2
hello 3

And C / C + + are different, then if the loop has multiple, break will exit the innermost loop.
outer = 0
loop do
outer + = 1

inner = 0
loop do
inner + = 1
print "Inner # (inner) \ n"
break if inner> 1
end

print "Outer # (outer) \ n"
break if outer> 1
end

Implementation of the results:
Inner 1
Inner 2
Outer 1
Inner 1
Inner 2
Outer 2

Another C / C + + language is a break in different places can only exit from the loop and not to withdraw from the case.

§ 6.9.6.2 redo
redo statement re-execution of the current cycle this time.

count = 0

for i in 1 .. 3
print "hello # (i) \ n"
break if count == 1

if i> 1
count + = 1
redo
end
end

Implementation of the results:
hello 1
hello 2
hello 2

The above example, the use of redo, the loop variable i's value or 2, showing the redo statement re-run the loop.

And break statements like, redo statement only works on the innermost loop.

3.times do
count = 0
for i in 1 .. 3
print "hello # (i) \ n"
break if count == 1

if i> 1
count + = 1
redo
end
end
end

Implementation of the results:
hello 1
hello 2
hello 2
hello 1
hello 2
hello 2
hello 1
hello 2
hello 2

§ 6.9.6.3 next
Next similar to the C / C + + in the continue statement jumps to the head of the current cycle, with the next cycle.

loop do
times + = 1
next if times == 2
print "hello # (times) \ n"
break if times> 3
end

Implementation of the results:
hello 1
hello 3
hello 4

And break, redo a similar, if the loop has multiple, then the next innermost loop only works.

outer = 0
loop do
outer + = 1

inner = 0
loop do
inner + = 1
next if inner == 1
print "Inner # (inner) \ n"
break if inner> 1
end

print "Outer # (outer) \ n"
break if outer> 1
end

Implementation of the results:
Inner 2
Outer 1
Inner 2
Outer 2

§ 6.9.7 Retry
The previous section we saw, you can use redo to re-execution of the current cycle of this time, and sometimes, we need to re-run the whole cycle, not just the implementation of the current this time, this time when we can retry. In the iteration, block or for statement using the retry, restart iterator means. At the same time the parameters of the iterator will also be recalculated.

An example is as follows,
for i in 1 .. 5
retry if some_condition # i == 1 starting from the re-run
end

Executable to see a complete example:
count = 0

for i in 1 .. 3
pr
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of ruby syntax tutorials

  • J2EEer Learn Ruby

    Ruby has long heard of the development of efficient and accurate is to use Ruby on Rails to develop WEB applications very convenient. While J2EE has a lot of very good Opensource framework, automatic code generation tools, can greatly enhance the developm

  • Topic: Shoes - Construction Ruby client gadget

    http://www.javaeye.com/topic/295829 Shoes Ruby are cross-platform GUI applications, recently released a new version, it is a very interesting Ruby GUI client, the following are some characteristics of Introduction: 1. Cross-platform support for windo ...

  • IE7 under, Rails link_to questions generated failure Confirm

    link_to property has a method often used with: confirm delete property to do the confirmation link. In fact, in the onclick link to create a temporary form, submit a request, and finally return false, so the link itself will not be triggered. However ...

  • Ruby Symbol

    Ruby is a completely cross-platform object-oriented scripting language, built on the Ruby-based Web framework Ruby on Rails (ROR) is the field of web development is gaining increasing acceptance. ROR substantial use of the Ruby language features, Symbol i

  • hibernate Technical Study Notes (first)

    Introduction: Model does not match (impedance mismatch) java object-oriented language, object model, its key concepts are: inheritance, association, polymorphism, etc.; database is the relational model, its key concepts are: tables, primary keys, for ...

  • Pyronaridine listing! Ruby programming language

    Interactive Net Purchase Excellence Amazon purchase [Original title] The Ruby Programming Language Publishing ] [ O'Reilly Media, Inc. [Author] (United States) David Flanagan; Yukihiro Matsumoto Translator [] LIAO Zhi-gang; Zhang Wo [Name] Books O

  • Shoes - Construction Ruby client gadget

    Shoes Ruby are cross-platform GUI applications, recently released a new version, it is a very interesting Ruby GUI client, the following are some characteristics of Introduction: 1. Cross-platform support for windows / linux / mac os 2. Very small, t ...

  • Object-oriented design principles 11

    What is object-oriented design? Contains what? The benefits of it are what? Required to pay what you do? In today's age, ask these questions seem to be foolish, because this year almost every software developer knows how to use some sort of objec ...

  • Hibernate pessimistic locking mechanism for locking and optimistic locking

    hibernate lock mechanism 1. Pessimistic lock It refers to the modification of data by outsiders hold a conservative attitude. The assumption that at any time access to data, may also have another client to access the same data, in order to maintain t ...

  • Nan-Jing 5: When IBatis.Hibernate mixed affairs, pay attention to your SQL

    [Problem] Now, in the development of the so-called multi-storey JavaEE applications, data persistence layer is always essential, and "Automatic" of ORM - Hibernate, and "all-manual-type" of SqlMap - IBatis, equivalent data are Per ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries