Some simple examples of ruby _ruby topics

Source: Internet
Author: User
Tags chop flush modifier rand regular expression stdin
Now let's analyze the code of some of the previous example programs Bache.

The following example appears in a simple Example section.

def fact (N)
If n = 0
1
Else
n * Fact (N-1)
End
End
print fact (argv[0].to_i), "\ n"


Because this is the first explanation, we will analyze it by line.

def fact (N)


The first line, DEF is used to define a function (or, more accurately, a method; we'll discuss in detail what a method is in a later section). Here, it indicates that the fact function takes an argument, that is, N.

If n = 0


If it is used to check for a condition. When the condition matches, execute the following code, otherwise execute the code following the else.

1


When the condition is set, the value of if is 1.

Else


If the condition is not tenable, execute the code from here to end.

n * Fact (N-1)


If the condition is not satisfied, the value of if will be the result of n multiplication fact (n-1).

End


The first end corresponds to an if statement.

End


The second end corresponds to the DEF statement.

print fact (argv[0].to_i), "\ n"


This sentence calls the fact () function with the value specified by the command line and prints the result.

ARGV is an array that contains command-line arguments. The argv member is a string, so we have to convert it to an integer by To_i. Ruby does not automatically convert strings to integers as Perl does.

Hmmm ... What happens if you assign a negative value to the program as an argument? Did you see the problem? Can you fix it?

Strings

Let's examine the guessing program that appears in this chapter of the string. Since this is a bit longer, we're going to hit each line in the uplink.

words = [' foobar ', ' baz ', ' Quux ']
Secret = Words[rand (3)]
03
Print "Guess?"
While guess = Stdin.gets
Modified guess.chop!
Modified if guess = = Secret
Print "You win\n"
Break
Ten Else
One print "You lose.\n"
End
Print "Guess?"
End
Print "The word is", secret, ". \ n"


In this program, we use a new control structure while. As long as a specified condition remains true, the code between the while and its corresponding end is repeated.

RAND (3) of row 2 returns a random number between 0-2. This random number is used to extract a member of the array words.

In line 5 We read a row from standard input through the Stdin.gets method. If EOF (end of file) is encountered by the read line, gets returns nil. Therefore, the code that is connected to the while is executed until it encounters the ^d (or DOS ^z), indicating the end of the input.

The guess.chop! of row 6 removes the last character of the Guess; it must be a line break.

Line 15, we print out the words to guess. The code we write is to pass three arguments to the print statement (these three parameters are printed one after the other), but it can also be printed equivalently with one argument: Write Secret as #{secret} to indicate that it is a variable to be evaluated. Rather than a generic text to print:

Print "The word is #{secret}.\n"


Regular expressions

Finally, let's take a look at the program in the regular Expression section.


st = "\033[7m"
En = "\033[m"
03
While TRUE
Print "Str>"
Modified Stdout.flush
Modified str = gets
The If not str
str.chop!
Print "Pat>"
One Stdout.flush
Re = gets
The If not re
re.chop!
str.gsub! Re, "#{st}\\&#{en}"
Print str, "\ n"
End
print "\ n"


The condition of the row 4,while is set to true, so this seems to constitute an infinite loop. But we placed a break statement in line 8 and row 13 to jump out of the loop. These two break statements are also an example of an if modifier (if modifier). an "if" Executes the statement to the left of it if and only if the specified condition is satisfied.

Again, chop!. (Row 9 and line 14 appear). In Ruby, we can also "!" and "?" Attached to some method names. exclamation point (!, sometimes read aloud as "bang!") Implying that something may be destructive (destructive) means that something can change what it touches. chop! directly acts on a string, but does not take! The chop will only produce a copy. Here's a demo of this distinction.

ruby> S1 = "Forth"
"Forth"
Ruby> s1.chop! # This changes S1.
"Fort"
ruby> s2 = s1.chop # This puts a changed copy in S2,
"For"
ruby> S1 ... without disturbing s1.
"Fort"



Later you will meet with a question mark (?, sometimes loudly read "Huh?") The End method name, which refers to the assertion (PREDIACTE) method, which returns TRUE or False only.

Line 15 should be paid attention to. First, notice that gsub! is also a destructive function. It modifies STR by replacing all the re pattern characters (sub-reference substitution, the first letter G refers to the global, for example, replacing all matches instead of just the first match). So far, okay; But what do we use to replace the matching part of the text? St and EN in rows 1 and 2 are respectively defined as ANSI codes that represent inverted text color (color-inverted) and restore normal text color. In line 15, they are surrounded by #{} to ensure that they are interpreted as defined previously (so that we do not see the variable names being printed). In the middle of this is "\\&". This is a trick. Because the replacement string is caused by double quotes, a pair of backslashes is interpreted as a single backslash; so Gsub ! What actually gets is "\&", a special piece of code just means "any character that matches the pattern in the first place." So the new string is printed, much like the original one, except that the matching part is displayed in a inverse video in the form of a high brightness.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.