官术网_书友最值得收藏!

Methods

Ruby methods are what we refer to as functions in some other programming languages. Many a times, we would want all the statements, operators, and so on that we saw earlier, to be bundled together and used as a single unit. Methods are means to accomplish this feat.

In Ruby, a method name should begin with a lowercase letter. Methods should be defined before they are called upon, otherwise an exception is raised by Ruby.

The syntax to define a method is as follows:

def method_name [([arg [= default]]...[, *arg [, &expr ]])]
end

Let's look at a few different examples to make this syntax more clear.

Example 1—a simple method:

def method
  # Method definition goes here
end

Example 2—a method with two arguments:

def method (arg1, arg2)
   #  Method definition goes here
end

Example 3—a method with two arguments having some default values. This will pass default values to the arguments if the method is called without passing the required parameters:

def method (arg1=val1, arg2=val2)   #  Method definition goes here
end

Example 4—variable number of parameters:

def method (*args)
  # Method definition goes here
end

In this case, args is an array that contains all the parameters that are passed to the method when it's called.

Each method in Ruby returns a value by default. This return value will be the value of the last statement of the method definition, or whatever is returned explicitly by the return statement.

Take a look at the following examples.

Example 1—default return value:

def method
  x=1
  y=2
end

This method, when called, will return the last declared variable y.

Example 2—explicit return value using the return statement:

def method
  return 1
end

This will return 1.

The method can be called by issuing its name. For example:

  • method #: This will call a simple method called method
  • method("a","b") #: This will call a method with two arguments
  • method "a","b" #: This will again call a method with two arguments

You may even assign a value of this method to a variable.

Blocks

Blocks are one of the most powerful features of the Ruby programming language and perhaps one of the most misunderstood ones. Blocks are pieces of code between braces ({}), or pieces of code enclosed between do-end. These are a way to group statements and they can only appear adjacent to method calls. The code written inside a block is not executed when it's encountered, instead it's called when the method makes a call to yield.

Blocks can have their own arguments as well. There are many methods in Ruby that iterate over a range of values, and most of them can take a code block as an argument. These methods call yield multiple times to allow for the iteration to complete.

Let's explore this using some examples.

Example 1—a simple code block:

Line1 #/usr/bin/env ruby
Line2 def call_block
Line3 i=0
Line4 puts "Start of method"
Line5 while i < 10
Line6 print i + ":\t"
Line7 yield
Line8 i += 1
Line9 end
Line10 puts "End of method"
Line11 end
Line12 call_block { puts "Inside code block" }

When executed, we'll get the following output from the preceding code:

Start of method
0: Inside code block
1: Inside code block
2: Inside code block
3: Inside code block
4: Inside code block
5: Inside code block
6: Inside code block
7: Inside code block
8: Inside code block
9: Inside code block
End of method

So, the interpreter looked at the code and figured out that we made a call to the call_block method in Line12. The interpreter then jumps to Line2 where the method is defined. Starting on Line5, we enter a while loop; finally, on Line7 we make a call to the block associated with the call_block method.

Example 2—a code block with arguments:

#/usr/bin/env ruby
def call_block
 i=0
 puts "Start of method"
 while i < 10
 yield i
 i += 1
 end
 puts "End of method"
end
call_block { |i| puts "Call #{i} - Inside code block" }

Here, we create a block that accepts an argument. The value passed to the block as an argument is stored inside a local variable named i. This time, inside the call_block method, we call the block through yield along with the argument. The following is the output of running this piece of code:

Start of method
Call 0 - Inside code block
Call 1 - Inside code block
Call 2 - Inside code block
Call 3 - Inside code block
Call 4 - Inside code block
Call 5 - Inside code block
Call 6 - Inside code block
Call 7 - Inside code block
Call 8 - Inside code block
Call 9 - Inside code block
End of method

Example 3—a code block using do-end

Both the previous examples made use of braces to declare a code block. Let's see how we can create a code block using the do-end directives:

#/usr/bin/env ruby
def call_block
 i=0
 puts "Start of method"
 while i < 3
 yield i
 i += 1
 end
 puts "End of method"
end
call_block do |i|
 puts "Call #{i} - Inside code block"
end

Again, as in the example 2, this code will generate the same output as the previous example:

Start of method
Call 0 - Inside code block
Call 1 - Inside code block
Call 2 - Inside code block
End of method

Example 4—let's see how we handle variable scoping with blocks:

#/usr/bin/env ruby
x=15
3.times do |x|
 puts "x in the block is #{x}"
end
puts "x out of the block is #{x}"

When executed, we'll get this output:

x in block is 0
x in block is 1
x in block is 2
x out of block is 15

So the x variable in the block was indeed a local variable.

Now let's see another case:

#!/usr/bin/env ruby
x=15
3.times do |y|
 x = y
 puts "x in block is #{x}"
end
puts "x out of block is #{x}"

When executed, we'll get this output:

x in block is 0
x in block is 1
x in block is 2
x out of block is 2

In this case, since x is not a block parameter (variables inside || are called block parameters), both occurrences of x inside and outside the block are one and the same.

There has been a change in how we can handle scoping of block parameters since Ruby 1.9. Since 1.9, blocks have their own scope for block parameters only. For example:

#/usr/bin/env ruby
x=15
3.times do |y; x|
 x = y
 puts "x in block is #{x}"
end
puts "x out of block is #{x}"

When executed, we'll get this output:

x in block is 0
x in block is 1
x in block is 2
x out of block is 15

Here, the x variable is a variable local to the block. If you want to specify variables local to the block, just add them as a comma separated list after adding a semicolon to the block parameter list.

For example, if a block has two block parameters, namely x and y, and you want to have two block local variables, a and b, you can specify them as: | x,y ; a,b |.

主站蜘蛛池模板: 理塘县| 阿尔山市| 电白县| 莲花县| 巨鹿县| 肃北| 靖安县| 沙湾县| 通州区| 江华| 舒兰市| 阿克苏市| 元江| 穆棱市| 当阳市| 广南县| 尼木县| 肃宁县| 新沂市| 尖扎县| 大同县| 仁布县| 辽中县| 县级市| 武定县| 左贡县| 敖汉旗| 灵石县| 嵊州市| 石门县| 普兰县| 图木舒克市| 前郭尔| 长兴县| 普洱| 辽阳市| 仪陇县| 灵川县| 穆棱市| 乌鲁木齐市| 嘉义市|