Suddenly, I met you-Ruby

Source: Internet
Author: User
Tags chop
From a stranger to a preliminary understanding; from reading to hands-on practice, I want to say, you are very beautiful!

Ruby is a pure object-oriented scripting language developed by yukihiro Matsumoto in Japan. This language is designed to control Text Processing (also related to regular expressions) and system management tasks.

From IBM: programming in ruby

As shown in the following example, anyone who has ever written scripting languages such as Perl or PHP will be familiar with Ruby syntax. However, Perl or PHP requires a semicolon as a line terminator. Ruby is different from them and does not require a line terminator. Some developers may be confused at first, but I find that this actually accelerates the development process. For example, I will no longer receive the "error missing; On Line X" message. To have a preliminary understanding of the Ruby world and elaborate on this idea, take a classic Hello world example:

Listing 1. Hello World

#! /Usr/bin/Ruby # My first ruby Program # print "Hello world \ n"



Back to Top

Variable

Variables in ruby are very easy to process. Let's extend the first example and introduce a simple method to change the output.

Listing 2. Changing the output

#! /Usr/bin/Ruby # My first ruby Program # declare our salutation $ salut = "good bye world \ n" # prepare statements print "Hello world \ n" Print $ Salut

Use$ SalutVariable. We can easily change the second variable at any time.PrintStatement output. You canProgramDeclare variables anywhere.

Listing 3. Declaring Variables

#! /Usr/bin/Ruby # My first ruby Program # $ salut = "good bye world \ n" print "Hello world \ n" Print $ salut # declare a new value $ salut. # $ salut = "Oh, I am sorry. I didn't mean to warnyou... \ n "print" what do you mean good bye world? \ N "Print $ Salut

If the preceding example is executed, the following content is output:

Hello worldgood bye worldwhat do you mean good bye world? Oh, I am sorry. I didn't mean to warn you...

As you can see, the variable's re-assignment takes effect.



Back to Top

Single quotation marks and double quotation marks

Like most languages, Ruby distinguishes between double quotation marks and single quotation marks. In Ruby, double quotation marks indicate that Ruby will interpret any value contained in the quotation marks. For example:

Print "Hello world \ n"

The Ruby interpreter escapes \ n and prints a linefeed to stdout (standard output ). However, if we want to execute the same statement with single quotes, for example:

Print 'Hello world \ N'

Ruby will output the following content:

Hello world \ n

Note that the new row is not printed. Instead, Ruby regards the entire statement as text, which is the same as what Perl uses.



Back to Top

Word Arithmetic

In Ruby, all strings can use operators. This means that we can perform arithmetic operations on words in a sense. For example:

$ Salut = $ salut * 3

The following results will be generated:

Oh, I am sorry. I didn't mean to warn you... oh, I am sorry. I didn't mean to warn you... oh, I am sorry. I didn't mean to warn you...

While

$ Salut = $ salut + "10, 9, 8..." Print $ Salut

The following results are generated:

Oh, I am sorry. I didn't mean to warn you... oh, I am sorry. I didn't mean to warn you... oh, I am sorry. I didn't mean to warn you... 10, 9, 8...

Note that although the variables are printed three times, the concatenation of "10, 9, 8..." is only printed once at the end of the program. Why?

The reason is that we only add "10, 9, 8..." to the end of the variable. We do not require the variable to add "10, 9, 8..." to each row. In addition, it is important to pay attention to the inheritance of the variables currently used.

Once a variable is assigned a value, it remains static unless it is assigned a value again.$ SalutSlave"Hello world \ n"Change to equal"What do you mean good bye world? \ N". However, this is not the case when the variables perform multiplication and concatenation operations. As you can see from the above example, using the concatenation (+ symbol) of a variable will cause this variable to inherit its previous assignment.AddThe string added to its value assignment. In our example, the added string is "10, 9, 8 ...".



Back to Top

Array

If you know that$ SalutHow do you assign values to variables? This can happen in many cases. Therefore, you can put all the variable values into a number group, instead of manually assigning a value to the variable.

The array allows processing of each variable value separately. See the following example:

$ Salut = ['Hello world', 'good bye world', 'What do youmean good bye world? '] Print $ Salut

Run the precedingCodeThe output is as follows:

Hello worldgood bye worldwhat do you mean good byeworld?

Obviously, this is not the output we want. There is no interval or line feed. Therefore, we can identify which part of the array we want to display and use the concatenation technology previously explained to provide easy-to-read output.

$ Salut = ['Hello world', 'good bye world', 'What do youmean good bye world? '] Print $ salut [0] + "\ n" Print $ salut [1] + "\ n" Print $ salut [2] + "\ n"

The output will be as follows:

Hello worldgood bye worldwhat do you mean good bye world?

Analyze the code carefully. If we review the created array:

$ Salut = ['Hello world', 'good bye world', 'What do youmean good bye world? ']

We told Ruby to defineSalutThe value is:

$ Salut = 0 1 2
Hello World Good bye world What do you mean good bye world?

Each value is identified by a number. The number is defined by the number position in the array. The position is always from0And starts to increase from 0. Therefore, to print the 2nd values in the array, enter:

Print $ salut [1]

The easiest thing to forget is that Fields0Instead1Start.



Back to Top

Condition-if, else

We have discussed the basics of displaying data in ruby. Now let's look at the preliminary knowledge about the logic in Ruby programming. That is to say, let us instruct the ruby program to execute basic functions based on the results obtained from the programmer. We also need to see how to execute conditional statements based on the results obtained by the ruby program from the user. New Code will be used in these examples.

Listing 4. Perform basic functions based on the results

$ Salut = ['Hello world', 'good bye world', 'What do youmean good bye world? '] Print "when you enter the world, what do you say? "While enterworld = stdin. Gets enterworld. Chop! If enterworld = $ salut [0] print "\ n" + "yes. hello World wocould bepolite. \ n "break else print" you say '", enterworld ,"'?! \ N "+" youhumans are so rude! \ N "end

The above code snippet introduces several new aspects of Ruby development. Let's browse these snippets.

Browse our example step by step

#! /Usr/bin/Ruby # My First interactive Ruby script # define our main variable with an array $ salut = ['Hello world', 'good bye world ', 'What do youmean good bye world? '] # Print my first question print "when you enter the world, what do you say? "# Create a while loop with the object enterworld andawait data from # standard input. the while loop will make sure thatruby continues # to process the application until the program tellsit to stop. while enterworld = stdin. gets # Make sure we use the chop method on the enterworldobject. the use # Of the chop method will insure that we strip newlines and carriage # returns from our input. # You will no Tice that using the chop method has anextra # character.! Allows the existing object to bemodified # By the method. If you did not use !, You wouldhave to redeclare # The enterworld object for the if condition tocorrectly occur. enterworld. Chop! # Begin the condition sequence. basically, ifenterworld equals # Hello world, which is 0, within the array, print # a new line. then print, "yes, hello World wowould bepolite. "to the screen. if enterworld = $ salut [0] print "\ n" + "yes. hello World wocould bepolite. \ n "# The break statement tells Ruby to stop executing ifthe previous # condition is met. if we did not include this in ourwhile loop, # The PR Ogram wocould run continuously. break # The else statement is used as the secondarycondition. in other # words, if the first condition is not met, please dothe following. else print "you say '", enterworld ,"'?! \ N "+" youhumans are so rude! \ N "break # The End statement is used to close a condition orloop. in our case, # It is being used to close both. we are first closingour if # condition statements and then stopping our whileloop. end end



Back to Top

Objects and Methods

Some techniques and methods used in this code segment may be the first time you have seen them. Ruby is an object-oriented Programming (OOP) language. When using OOP, programmers usually call projects such as objects and methods.ObjectIt is like a container. It contains its own specific variables and functions.MethodIt is a called thing, just like a function that specifically processes objects. If you look at the previous example, we can display the objects and methods in the work.

While enterworld = stdin. Gets enterworld. Chop!

Here we have two objects and two examples of methods. The first object isEnterworldThe second object isStdin.EnterworldObjects are user-defined objects, whileStdinObjects (abbreviated as standard input) are built in ruby.

There are two methods in this example. The first type isGets, The second isChop!. As mentioned above, methods are used to process objects. Specifically, the method will perform an operation in the object. UseGetsMethod, we will tell Ruby to getStdin. When Ruby seesStdinAssociatedGetsIt will wait for the keyboard input and a carriage return. In short,Stdin. GetsWait for the user to enter some content and then press Enter.

Method 2Chop!Used for user-defined objectsEnterworldFor special processing.Chop!Method descriptionEnterworldSetEnterworldThe linefeed and carriage return of the data associated with the object. If you do not useChop!(OrChomp!), The following statements contained in the context of the previous Code will never be true.

If enterworld = $ salut [0]

Because it is not usedChop!So the result is false,$ Salut [0]Actually, it is equal$ Salut [0] \ n. The new line is composedStdinObject slaveGetsMethod. If you press enter, a line break is added to the end of the value.



Back to Top

Conclusion

Ruby is a very powerful and easy-to-use language. If you are a programmer from C ++, Perl, or Python, you will find that they are very similar to Ruby (especially Python ). Next in this seriesArticleBased on this introduction, we will discuss more advanced topics, such as using the Roby module and file operations.



Back to Top

References

    • For more information, see

    • for more Ruby basics, including interviews with Ruby creator yukihiro Matsumoto, see "Ruby: a new language" on developerworks ".

    • refer to the official Ruby web site.

    • visit the ruby field.

    • learn more about Ruby in Ruby details.

    • find more information about Ruby for Win32.

    • Please stop at Ruby central.

    • Please refer to the ruby application file, which is maintained by ruby.

    • refer to the simple list of Ruby functions, which contains a brief discussion about Ruby's advantages and disadvantages (English and German ).

    • see the latest Ruby file updates in filewatcher.org.

    • read Ruby for Windows users.

    • visit Joshua Drake's Web site command prompt.

    • visit developerworks to learn more about Linux.

    • visit more open Source Code references on developerworks .
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.