Http://developer.51cto.com/art/200703/41243.htm
Introduction
This is a short Ruby entry, and it takes only 20 minutes to complete. Here we assume that you have installed Ruby. If you have not installed Ruby, visit the official Ruby website to download and install it.
Interactive Ruby
Open IRB (Interactive Ruby shell ):
If you use Mac OS X, open the terminal window and enter IRB;
If you are using Linux, Open Shell and enter IRB;
If you are using Windows, find Ruby-> fxri in the Start menu and execute it.
OK. After enabling IRB, enter "Hello World ".
Ruby follows your schedule!
What happened? Have we compiled the shortest "Hello World" program in the world just now? This is not accurate. The second line of output shows the evaluation result of the previous expression. If we want to print "Hello World", we still need to work hard:
Puts is a simple print output command in ruby. "=>
What does nil mean? -- That is the result of the expression. Puts always returns nil, which indicates "absolutely no value" (absolutely-positively-
Nothing value) method, it seems that some are similar to the null in Java.
Your free calculator is here!
Without doing anything, we can use IRB as a simple calculator:
In this way, 3 + 2 can be calculated. Simple enough! So how is 3 multiplied by 2? You can enter 3*2 below, or go back to the above (3 + 2) and modify the formula you just entered. Use the up key on the keyboard to move the cursor to the 3 + 2 line, move the cursor to the plus sign with the left button, and then use the space key for modification.
Next, let's calculate the square of 3:
In Ruby, ** indicates a power operation. How can we calculate the square root?
OK. Wait, what is SQRT (9) in the expression? You can guess that this is the square root of 9. What does math mean? Don't worry. Let's take a closer look at modules like math.
Module-code grouped by topic
Math is a built-in Mathematical Module of Ruby. In Ruby, the module provides two types of roles: A Role aggregates similar methods in the same "home"
. Therefore, math also includes methods such as sin and tan. The second role is a dot, which marks the receiver of the message. What is a message? Example above
In, SQRT (9) is the message, which means that the square root of 9 is retrieved by calling the SQRT method.
The result of the SQRT method call is 3.0. You may notice that it is not 3. This is because in most cases, the square root of a number is not an integer, so a floating point number is returned.
So how do we remember these computing results? -- Assign the result to the variable.
How to define a method?
How can we easily output strings without worrying about our fingers? -- We need to define a method!
The first line in the above code is "def
H indicates the beginning of the method definition. It tells Ruby that we are defining a method named H. The following line shows the method body: puts "Hello
World ". Finally, the third line "end" notifies Ruby that the method definition has been completed. Ruby's response "=>
"Nil" tells us that it knows that we have defined this method.
Call methods briefly and repeatedly
Now, let's try to execute this method multiple times:
Ha, this is too easy. To call a method in Ruby, you only need to submit the method name to Ruby. Of course, this is when the method has no parameters. You can add a blank bracket if you want, but this is unnecessary.
If we want to say hello to someone rather than the whole world, what should we do? -- Redefines the H method so that it receives the name parameter.
Well, it seems to work normally now.
Mysteries in strings
What does "# {name}" mean? This is how Ruby inserts other characters into a string. The string (name here) placed between braces will be replaced by an external string. You can also use the built-in capitalize method of the string class to ensure that the first letter of a person's name is capitalized:
The above code has two points to describe:
First, we call the method without parentheses, because parentheses are optional;
Second, the default parameter value here is "world ". That is to say, if the name parameter is not provided when a method is called, the default value "world" is used ".
Evolved to greeter!
Do we need a real greeting who can remember your name and greet you and always show you respect? Therefore, it is best to create a "greeter" class:
In the above class code, a class called greeter and some class methods are defined, and some new "keywords" appear: Please note "@ name ", it is an instance variable of the class and is valid for all methods in the class (say_hi and say_bye.
How to make the greeter class play a role? Now let's create a greeter object and use it!
After the greeter class instance object G is created, it accepts the name parameter (value: Pat ). Can we directly access the name?
Looking at the above compilation error, it is impossible to directly access the name.
Inside the object
The instance variables in the object are always hidden in it, but they are not traceable. They will be seen through the Audit object. Of course there are other access methods, but Ruby adopts a good object-oriented method to keep data hidden.
Oh! So many methods, but we only define two methods? Where do other methods come from? Don't worry. The instance_methods method lists
All methods, including the methods defined in the parent class. If we only want to list the methods of the greeter class, call false as the parameter.
You can use the instance_methods method. False means that the method defined by the parent class is not required.
Haha, this is what we want. Next let's take a look at the methods that the greeter object can respond:
It knows say_hi and to_s (this method converts an object to a string, which is a required default method for any object and misses the tostring method in Java), but it does not know the name.
Modify class definitions at any time
How can I view or modify the name? Ruby provides a simple way to access object variables:
In Ruby, you can open a class multiple times and modify it. Changes brought about by modifications will be applied to any new objects created after this, or even existing such objects. Next, let's create a new object and access its @ name attribute.
We define two methods by using attr_accessor:
". Name" is used to obtain the name attribute value;
". Name =" is used to set the namee attribute value.
This is similar to accessing the public modified member variables in Java classes.
Greetings to everyone. megagreeter won't miss a person.
Greeter is not perfect because it can only serve one person at a time. So here we design a megagreeter class that can send greetings to everyone in the world or to anyone on the List. Here, we will discard the previous IRB interaction mode and switch to writing Ruby program files.
To exit IRB, enter "quit" and "exit", or press control + D.
Save the above Code to the file "ri20min. RB" and run the "Ruby ri20min. RB" command. The program output is as follows:
Next we will take a closer look at the above Code.
Note that the starting line in the above Code starts. In Ruby, any line starting with # is considered as a comment and ignored by the interpreter.
Our say_hi method has changed:
It looks for the @ names parameter and makes a decision based on its parameter value:
If the parameter value is nil, it prints three dots.
So @ names. respond_to? ("Each") indicates what?
Loop-also called Iteration
If the @ names object has an each method, it can be iterated and then iterated to greet everyone in the list. If @ names does not have the each method, it is automatically converted to a string and the default greeting is executed.
Each is a method that accepts a block
Code), and then execute this code block for each member in the list. The part between do and end is a code block that is very similar to an anonymous function. The variable between pipeline operators is the parameter of the code block.
Name, which is bound as a list member as a code block parameter, and the code block puts "hello # {name }! "This parameter will be used for output.
Most other programming languages use the loop traversal list. Below is a loop example of C language:
The above code can obviously work, but it is not "elegant "! You have to use the excess loop variable I. You also need to specify the length of the list and then explain how to traverse the list.
Ruby's iteration method is more elegant, and all internal management details are hidden in the each method. What you need to do is to tell it how to process each member.
Block, a highlight of the Ruby edge!
The real advantage of block is that it can process more complex objects than List objects. In addition to handling simple internal management details in methods, you can also handle setup, teardown, and all errors without being noticed by users.
The say_bye method does not use each, but checks whether @ names has a join method. If there is a join method, the join method is called. Otherwise, it will print the @ names variable directly.
This method does not care about the actual type of the variable. It depends on the types supported by the variable called "duck typing"
Method: Duck
Typing is a form of dynamic type: the value of a variable implicitly determines the behavior of a variable. This implies that an object can be exchanged with other objects that implement the same interface, regardless of
Whether it has an inheritance relationship. The duck test is for the duck
Typing is an image metaphor-"if it walks like a duck, it must also be called as a duck, then it must be a duck ". Duck
Typing is a feature of some programming languages, such as Smalltalk, Python, Ruby, and ColdFusion.
The benefit of duck typing is that you do not need to strictly limit the type of the variable. If someone uses a new type of List class, as long as it implements the join method with the same semantics as other lists, you can use it.
Start script
The upper part of the file is the megagreeter class code, while the remaining part is the call to these class methods. This is the last point worth noting:
_ File _ is a "magic" variable that represents the current file name. $0 is the name of the file used to start the program. Then the code "If
_ File _ =
$0 "means to check whether this file is the main program file to be used. In this way, the program file can be used as the code base instead of executable code. However, when the file is used as the execution file, it can also be executed.
Line.
How to further learn Ruby
This is the end of this article. Of course there are still a lot worth browsing: Ruby provides a variety of different control structures, the use of blocks and yield, and the use of modules as mixins. We hope that this early Ruby experience will make you more interested in ruby.
Note:In object-oriented programming languages, Mixin is a class that provides certain functions to inherit from sub-classes. However, Mixin cannot be instantiated. From
Mixin inheritance is not a special form, but it is more suitable for collection functions. A subclass can even inherit all or most of its functions by inheriting one or more mixins. One
Mixin can extend definition and bind methods until runtime, and attributes and instance parameters will not be defined during compilation. This is different from most common methods: define all attributes and methods, and perform initial operations during compilation.
.