Some simple ruby examples

Source: Internet
Author: User
Tags chop

Now let's take a look at the code of some previous sample programs.

The following example is shown in the 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 row by row.

Def fact (n)


In the first line, def is used to define a function (or, more accurately, a method); we will discuss in detail what is a method later ). here, it indicates that the fact function carries a parameter, that is, n.

If n = 0


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

1


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

Else


If the condition is not true, run the code from here to end.

N * fact (n-1)


If the condition is not met, the if value is the result of n multiplication fact (n-1.

End


The first end corresponds to the if statement.

End


The second end corresponds to the def statement.

Print fact (ARGV [0]. to_ I), "\ n"


Use the value specified by the command line to call the fact () function and print the result.

ARGV is an array containing command line parameters. ARGV is a string member, so we must convert it to an integer through to_ I. Ruby does not automatically convert the string to an integer like Perl.

Hmmm... what if a negative value is assigned to the program as a parameter? Have you seen this problem? Can you fix it?

Strings

Next, let's check the riddle program that appears in the character string chapter. Because this is longer, we add the number of rows for each row.

01 words = ['foobar', 'baz', 'quux ']
02 secret = words [rand (3)]
03
04 print "guess? "
05 while guess = STDIN. gets
06 guess. chop!
07 if guess = secret
08 print "you win \ n"
09 break
10 else
11 print "you lose. \ n"
12 end
13 print "guess? "
14 end
15 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 end will be executed repeatedly.

Rand (3) of Row 2 returns a random number between 0 and 2. This random number is used to extract a member from the array words.

In row 5, we use STDIN. the gets method reads a row from the standard input. if the read row encounters an EOF (end of the file), gets will return nil. therefore, the code connected to the while statement will be executed until it encounters ^ D (or ^ Z under DOS), indicating the end of the input.

Line 6 guess. chop! Remove the last character of guess; it must be a line break.

Row 15: Let's print the words to guess. the code we write is to pass three parameters to the print statement (the three parameters are printed one by one), but it can also be printed using one parameter: write secret as # {secret} to indicate that it is a variable to be taken, rather than a general text to be printed:

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


Regular Expression

Finally, let's look at the program in the regular expression section.


01 st = "\ 033 [7 m"
02 en = "\ 033 [m"
03
04 while TRUE
05 print "str>"
06 STDOUT. flush
07 str = gets
08 break if not str
09 str. chop!
10 print "pat>"
11 STDOUT. flush
12 re = gets
13 break if not re
14 re. chop!
15 str. gsub! Re, "# {st }\\&# {en }"
16 print str, "\ n"
17 end
18 print "\ n"


In Row 4, The while condition is hard set to true, so it seems to constitute an infinite loop. however, we place the break statement in rows 8 and 13 to exit the loop. these two break statements are also an example of if modifier. A "if modifier" is executed only when the specified condition is met.

Let's talk about chop! (Lines 9 and 14). In Ruby, we can also set "! "And "? "Appended to some method names. Exclamation point (!, Sometimes I read it as "bang! ") Implies that something may be destructive (destructive), that is, something can change what it involves. chop! Directly act on a string, but it does not contain! Only one copy is generated. The following is a demonstration of this difference.

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



You will see a question mark (?, Sometimes, I read "huh? ") End method name; this refers to the" prediacte "(prediacte) method, only true or false is returned.

Line 15 should be noted. First, pay attention to gsub! It is also a damage function. it modifies str by replacing all characters that match the re pattern (sub indicates replacement, and the first letter g indicates global characters, for example, replacing all matches instead of the first match ). so far, it's okay; but what should we use to replace the matching part in the text? The st and en in Row 1 and row 2 are defined as the ANSI codes that indicate the reversed text color (color-inverted) and restored normal text color, respectively. in row 15, they are enclosed by # {} to ensure that they are interpreted as defined above (so that we don't see the variable name printed out ). in the middle is "\\&". this is a trick. because the replacement string is caused by double quotation marks, a backslash is interpreted as a single backslash. Therefore, gsub! The actual result is "\ &". A special code exactly represents "any character that matches the pattern at the first place ". therefore, when a new string is printed, it is similar to the original one, but the matching part is displayed in an inverse video mode.

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.