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