In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to use the block of Ruby". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this article "how to use the block of Ruby" can help you solve the problem.
1. A block is a piece of "semi-free" code that is outside the method and inside the soul-returning method.
The block code is delimited by {...} or do...end.
[1, 2, 3] .each {| I | I + 1}
Block (block) code can not be called alone, can only be attached to the method, so it is called soul return method.
two。 The block belongs to itself, and the only way to be completely free is to objectify it.
The soul belongs to itself, which means that it is completely free and can be called separately.
Proc.new {puts "hello"} proc {puts "hello"} proc {| msg | puts "hello # {msg}"} lambda {puts "hello"} lambda {| msg= "world!" | puts "hello # {msg}"}-> {puts "hello"}-> (msg= "world!") {puts "hello # {msg}"}
These are all the block objects provided by Ruby, which are objects of the Proc class.
3. It is your freedom to use block or not, but the method is born to be the soul of the block.
You can pass a block to any method in Ruby.
Def test;end test {puts i}
The above code doesn't even report an error because the block (block) is not used inside the test method.
Obviously, you can no longer think of block as that regular method parameter, even though it behaves like a parameter.
4. How to use block directly determines its fate!
a. Use the yield keyword inside the method to refer to the "soul" of block.
Def test yield end test {puts "hello test!"} def test (x) yield (x) end test ('Worldwide') {| x | puts "hello # {x}"}
The yield keyword not only mounts the block code, but also passes parameters to the block.
b. Soul-returning style: use "&" to make a block passed to the method return to itself.
Def test (& block) block.call ("world") end test {| msg | puts "hello # {msg}"}
But inside the method, you can also use "&" to spook the block object (Proc object):
Def test (& block) inner_test (& block) end def inner_test yield ("!") End test {| msg | puts "hello # {msg}"}
What a sinister method! Are there any?
5. The jealous block brothers.
{...} and do... End, although is a block twin brother, but there is also a who comes after, pay attention when using them, otherwise they will let you know who is the boss!
Def test (block) block.call end test lambda do puts "hello" end
You pass a free Proc object to the test method, but with a slight difference, this Proc object uses do...end, but after you execute the code, you will find that this code throws an exception: ArgumentError: tried to create Proc object without a block
Test (lambda do puts "hello" end)
It must be modified so that it can be executed normally. Or use:
Test lambda {puts "hello"}
This will also work properly.
As you can see, do...end is not as priority as {.}. {...} is close to the nearest lambda, while do...end is close to the farthest test.
Do...end feels a bit confusing, so when passing a Proc object to a method, be sure to use parentheses or {.}
However, because of the exception thrown, ArgumentError: tried to create Proc object without a block, we can get a way to implicitly pass block to the method:
Def test proc_obj = Proc.new proc.call end test {puts "hello"} 6. Block also has self-esteem. Def test x = 1 yield (x) end x = 2 test {puts x}
Block (block) has an ability to penetrate scope. In the above example, block does not use the variable Xblocks 1 in the test method, but grabs the variable Xblocks 2 outside the scope of the block (block).
7. For block's self-esteem, ask you (Rubyist) for help! Def test x = 1 yield (x) end x = 2 test {| x | puts x}
You (Rubyist) insert a parameter into the block (block), which immediately leaks. I can't thank you enough, and you hold your head up proudly.
8. Block (block) is still not satisfied! Turn to you (Rubyist) for help and restore his freedom!
You (Rubyist) block realize the free body and use lambda to objectify the block.
Def test x = 1 lambda {puts x} end lambda_proc_obj = test lambda_proc_obj.call
Now the lambda_proc_obj is out of breath, and lambda_proc_obj can call it whenever it wants (lambda_proc_obj.call).
Lambda_proc_obj thought: "I have packed up your method. I have your data, and I will never look at your face again." "
Oh, I see. If a block becomes a Proc object after it is completely free, it will have the superpower of closures. How terrible!
9. Two kinds of block objects (Proc objects), two kinds of fate, sadly lamentable!
a. Enslaved by methods: code snippets that must be executed
Proc_obj = Proc.new {return "from proc return"} # proc_obj = proc {return "from proc return"} def test (block) msg = block.call puts "hello! # {msg}!" End test (proc_obj)
This code throws a LocalJumpError exception. Proc objects defined with Proc.new and proc {} cannot use return.
This means that the Proc object, once it is call, must be executed.
Notice here that the test method passes an object that is itself Porc, without using &.
Take a look at this code again to see how concerned the two Proc objects are about arity (whether to check the number of parameters of the block object)
Def call_with_too_many_args (closure) begin puts "closure arity: # {closure.arity}" closure.call puts "Too many args worked" rescue Exception = > e puts "Too many args threw exception # {e.class}: # {e}" endend def two_arg_method (XMague y) endputs "Proc.new:"; call_with_too_many_args (Proc.new {| xjingy |}) puts "proc:" Call_with_too_many_args (proc {| XQuery |})
This code shows that the proc object defined by Proc.new or proc {} is completely a slave to the method.
The work must be done without saying (cannot be return), and no matter how many parameters are passed, you can't complain at all! Zombie? Slaves?
b. An anonymous method body
Lambda_proc_obj = lambda {return "return from lambda proc"} # lambda_proc_obj =-> {return "return from lambda proc"} def test (block) msg = block.call puts "hello! # {msg}!" End test (lambda_proc_obj)
You can see that the lambda proc object can be returned normally.
Puts "lambda:"; call_with_too_many_args (lambda {| Xjuny |})
This code, you can see that the Proc object created by lambda {} is the real free block object!
Take a rest when you want to work (you can return). If you pass on more parameters, you can also complain.
The free air is so nice.
It seems that lambda proc and Method objects are somewhat similar:
Puts "Method:"; call_with_too_many_args (method (: two_arg_method)) 10. You (Rubyist) have four ways to yell at poor chunks. Lm_proc_obj = lambda {puts "hello world!"} lm_proc_obj.call lm_proc_obj. () # No parameter must give an empty parenthesis lm_proc_obj [] # No parameter must give an empty square bracket lm_proc_obj = lambda {| msg | puts "hello # {msg}!"} lm_proc_obj.call ("world") lm_proc_obj. ("world") lm _ proc_obj ["world"] lm_proc_obj = = "world"
When you see the fourth way, you should think that you can use proc objects in case statements, right?
Def response_code? (code)-> (response) {response.code = = code} end case response when response_code? (200) then 'OK' when response_code? (404) then' Not found' else 'Unknown code' end on "how to use block in Ruby" ends here. Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.