Ruby yield keyword usage examples

Source: Internet
Author: User



Yield keyword I understand this, use it to occupy a position, first mark the next place in the future to write code, wait until the call, then write the specific code. A bit like a function pointer, or a delegate in C #, but it's not quite the same.



When writing the test interface, the Assert return value is not the same each time, but the function body is mostly the same, only the parameters are different. Just recently saw yield, familiar with the use, you can put the assert this part of code written in the position of yield.



The main example is the definition of this function and its invocation test_nodes.



Code:


 
 1 def generate_nodes(n=3)
 2     return n
 3 end
 4 
 5 def add_nodes(url,node)
 6     if node % 2 == 0
 7         return "message", 200
 8     else
 9         return "error", 500
10     end
11 end
12 
13 def test_nodes(nodes)
14     nodes.each do |node|
15       2.times do
16           #somecode       
17           restr, rcode = add_nodes("url",node)
18           yield restr, rcode, node
19       end
20    end
21 end
22 
23 nodes_list = [generate_nodes, generate_nodes(4),generate_nodes(5),generate_nodes(6)]
24 
25 test_nodes(nodes_list) do |restr, rcode, node|
26     if restr == "message" && rcode == 200  then #assert return value
27         puts "success"
28     else
29         puts "failed: node is #{node}"
30     end
31 end





Ruby yield keyword usage examples


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.