What does this ruby code mean

  question, ruby

Recently, I am studying elk and need to embed ruby code. I hope I can help you understand ruby. Please explain, thank you!

Just explain what each of the following two parts represents.

//The first one
 xx "xxx" do
 
 end
 //The second kind
 xx("xxx") do |xx|
 
 end

The original code is as follows

test "drop percentage 100% " do
 
 parameters do
 {"percentage"=>1}
 end
 
 in_event {{"message"=>"bonjour bonjour","date"=>"2018-2-2"}}
 
 
 expect("drops the event") do |events|
 puts "-------->expect"
 events.size == 0
 end
 end

This code is a unit test. The explanation is roughly as follows:

parameters do
 {"percentage"=>1}
 end

The meaning of this code is that parameters is a function without parameters. this function can be embedded into the yield part of the function to perform operations with a code block, that is, do…end. for example, here an assignment operation is given to the parameters function.

How to use this yield? Look at the following example:

# Define Function test
 def test
 puts '1'
 Yield # is provided here for code block execution
 puts '3'
 end
 test do
 Puts '2' # Code Block Specific Execution Content
 end

Then output 1, 2, 3

Similarly,

expect("drops the event") do |events|
 puts "-------->expect"
 events.size == 0
 end

Here is a function with parameters, followed by a code block. The function is expect to make a test assertion. The parameter “drops the event” is the description of the assertion-I hope to throw away all the events. Then the function can give a parameter when yield, and let the code block use yield(events). For example, take out the events here, and the code block will determine that the events.size is 0.

This expect function is roughly defined as follows:

def expect(describe)
 Events = [] # Do an operation to empty events
 Result = yield(events) # Takes events as a parameter and shows it to the outside code block
 if result == true
 Puts' Assertion Successful'
 else
 Puts' assertion failed'
 end
 end

When you look at the specific use, the code block determines events.size == 0, and then the result true is assigned to the result in the expect function, and the expect function continues to execute.

In addition, the code blocks are not only do…end and do |unit| … end, here {…} after in_event is also a code block, the content of the code block is {“message” = > “bonjour bonjour”, “date” = > “2018-2-2”} this hash, and there is another code block used by {|unit|…}. In other words, you can regard the opening brace as do and the closing brace as end.

I hope I can help you.