Programming ruby-code block, iterator, and input/output

Source: Internet
Author: User

CodeBlock and iterator

This section briefly introduces one of Ruby's features. What we will learn is code blocks: Some codes that can be associated with methods to call them together, just like the parameters of methods.

This is an incredible powerful feature. One of our critics commented on this feature as follows: "This is really interesting and important. If you haven't noticed it before,

Now you have to pay attention to it ." We all agree with him.

You can use code blocks to implement callback (but they are much simpler than Java's anonymous inline functions), pass in a code block (but they are much safer than C's method pointers), and then implement iteration.

A code block is just some code between curly braces or do... end.

  {Puts  "  Hello  "  }  # This is a block  
Do # ##
Club. Enroll (person) # And so is this
Person. Socialize #
End # ##

Why are there two separators? One of the reasons is that sometimes one of them feels more natural than the other. Another reason is that they have different priorities: curly braces have higher priority than do/end pairs.

In this book, we will try our best to follow the ruby standard usage, use curly brackets for a single line of code, and use do/end for multiple lines of code.

Once you create a code block, you can associate it with a method for calling. You just need to put the code block after the code that contains the method call.

For example, in the following code, a code containing puts "hi" is associated with a greet method call.

 
  Greet {puts"Hi"}

 

If the methods contain parameters, place them in front of curly brackets.

  Verbose_greet ("Dave","Loyal customer") {Puts"Hi"}

 

 
 

Using Ruby's yield, a code block associated with the method can be executed once or multiple times. You can think of yeild as a method call, which can call a code block associated with a method containing yield.

The following is an example. We define a method that calls yield twice, put the code block on the same line as the method, after the method call (and after all the parameters of the method ).

Code 
Def Call_block
Puts " Start of Method "
Yield
Yield
Puts " End of Method "
End
Call_block {puts " In the block " }
Produces:
Start of Method
In the block
In the block
End of Method

 

Take a closer look at how the code (puts "in the block") in the code block is executed twice, and one yield is executed once.

You can provide parameters when calling yield: these parameters are passed to the code block. In a code block, you can list the names of parameters to be received between two vertical bars (|.

Code
DefCall_block
Yield("Hello",99)
End
Call_block {|STR, num|}

 

Code blocks are used throughout the ruby class library for iteration: a method that can return continuous elements from various sets, such as arrays.

  Animals= %W (ANT bee cat dog elk)#Create an array
Animals. Each {|Animal|Puts animal}#Iterate over the contents
Produces:
Ant
Bee
Cat
Dog
Elk

 

 

Let's take a look at how the array class uses code blocks to implement each iteration in the above example. Each element in the each iteration loop array calls yield.

In pseudo code, they may look like this

 
  #Within class Array
DefEach
ForEach element#<Not valid Ruby
Yield(Element)
End
End

 

 
 

ManyProgramming LanguageFor example, the built-in loop structure of C and Java is only a simple method call in Ruby, and the code block associated with the method is called 0 times or multiple times.

  [  '  Cat  '  ,  '  Dog  '  ,  '  Horse  '  ]. Each { |  Name  |     Print  Name,  "     "  }
5 . Times { Print " * " }
3 . Upto ( 6 ){ | I | Print I}
( ' A ' .. ' E ' ). Each { | Char | Print Char}
Produces:
Cat dog horse ***** 3456 ABCDE

 

 
 

Here, Let object 5 call the code block five times, let object 3 call a code block, and pass it a continuous value from 3 to 6. Finally, each character in the range from A to E calls the code block once.

Input and Output

Ruby comes with a comprehensive I/O library. However, in most examples of this book, we still use some simple methods. We have used two methods for output.

Puts outputs its parameters and forwards them to the next row. Print is also a parameter for output, but it does not wrap. They can be used to output to any I/O object, but are output to standard output by default.

Another output method we use is printf, which outputs parameters under the control of the format string (the same as printf in C or Perl ).

  Printf ("Number: % 5.2f, \ nstring: % s \ n",1.23,"Hello")
Produces:
Number:1.23,
String: Hello

 

 
 

In this example, the formatted string "number: % 5.2f, \ nstring: % s \ n" tells printf to use a floating point number (a total of five characters are allowed, two of which are after the decimal point)

And a string replacement. Note that the line break (\ n) is in this string; each line break uses the output to switch to the next line.

You can read the input in multiple ways.Program. Perhaps the most classic is the use of commonly used gets, which returns the next row of the standard input stream to the program.

 
  Line=Gets
PrintLine
 
 
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.