Deep understanding of code block blocks in Ruby _ruby topics

Source: Internet
Author: User

What's block?

In Ruby, block is not uncommon. The official definition of block is "a parcel of code". Of course, I don't think this explanation will make you more aware.

A simpler description of block is "a block is a piece of code stored in a variable that, like any other object, can be run at any time"

Then, let's look at some code and then refactor the code to form the block in Ruby. Through the code to the actual feeling, more intuitive.

For example, do you add two numbers?

Puts 5 + 6
# => 11

Well, it's OK to write this. However, such code only has the first half of the block definition-it's a piece of code. But it's not "wrapped up" or "stored in a variable."

So, we need to keep revising. But before wrapping it up, let's improve it to make it look more generic.

A = 5
B = 6
puts A + b
# => 11

OK, that's it--we replaced the previous number with a variable. This code performs a summation process, but it is still not stored in a variable.

Now, let's make it happen.

Addition = lambda {|a, b| return a+b}
puts Addition.call (5, 6)
# => 11

Well, now you're wrapping it up nicely--that's a block!.

Using the ' lambda ' keyword is the most common way to create blocks in Ruby. There are other ways to do it, but let's do it the other way.

At this point, you might think, "Wait, this thing looks like a method, except there are no classes or objects." You're right. You can even understand that a block is like a method, but it is not associated with any object.

Let's go ahead and take a closer look at block.

Blocks of code that a block contains. You can assign a name to a block. The code in the block is always enclosed in curly braces ({}) or do...end.

[1, 2, 3].each do |i|
 Puts I
end

#=> 1
  2
  3

In the example above, each method is followed by a do...end structure, which is a block.

Any method in Ruby you can pass a block.

  def test;end
  test{puts i}

def test
  yield
 end
 test{puts "Hello test!"}

 def test (x)
  yield (x)
 end
 test (' world! ') {|x| puts "Hello #{x}"}

The yield keyword can not only mount block code, but also pass parameters to the block.

def test (&block)
  Block.call ("World")

 end test{|msg| puts "Hello #{msg}"} blocks
to the inside of the method, has been & Converted to a Proc object.

 def test (&block)
  inner_test (&block)
 end

 def inner_test
  yield ("haha!")
 End

 test{|msg| puts "Hello #{msg}"}

The block that the test method passes into is transformed into a proc object, and its internal inner_test uses "&" to transform the proc object into blocks.

is block the object? Of course, like everything else in Ruby, Block is also an object.

Empty_block = lambda {}
puts empty_block.object_id
# => 28765760 puts Empty_block.class
# => Proc
puts Empty_block.class.superclass
# => Object

As you can see, the block we created has a object_id, belongs to the Proc class (this is the name of a block in Ruby), and the class itself is a subclass of object.

We can even, in turn, define the method from the block. A method is a block that binds an object so that it can access the object's state.

Let me show you how to create a block in reverse using a method. There are some more traditional ways to implement the previous question (and please forgive me for poor object modeling)

Class Calculator
 def add (A, b) return
  a+b
 end

puts Calculator.new.add (5, 6)
# => 11

This code of course can work well. Then, make a little change.

Class Calculator
 def add (A, b) return
  a+b
 end

addition_method = Calculator.new.method (" Add ")
addition = Addition_method.to_proc

puts Addition.call (5, 6)
# => 11

Now, you convert a traditional method to a block!

Block your code!

Let's construct 4 blocks, respectively, for subtraction operations. Each block should accept two values as a variable, and then perform the action and return the result.

Addition = lambda {|a, b| return a+b}

subtraction = lambda {|a, b| return a-b}

multiplication = lambda {|a, b| Return A*B}

Division = lambda {|a, b| return/a

/A/A/A/a when used by call to use
Addition.call (5, 6)
# => 11

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.