What is the difference between lambda and block start?

I am trying to check if the text was written to the file (build.log) after running the rake command that throws an exception. Inspect both code snippets below, one that starts with work, while lambda throws a message stating that it cannot find the build.log file.

Using the start of testing. (works)

begin Rake::Task['git:checkout'].invoke //writes "destination already exists" to build.log rescue end IO.read(@ project_folder+@build _id+"/build.log").should match(/.*destination.*already.*exists.* /) 

Trying to check the same using lambda. (Does not work)

  lambda { Rake::Task['git:checkout'].invoke //writes "destination already exists" to build.log } IO.read(@ project_folder+@build _id+"/build.log").should match(/.*destination.*already.*exists.* /) 

What is the difference between the two?

+4
source share
1 answer

You think about lambda wrong. Lambda is a suspension of executable code. I say it is suspended because it is ready to be launched, even ready to accept arguments, but nothing has really been done.

For example, consider the following (missing) specification:

 flag = false x = lambda { # Here, we suspend a function to set our flag. flag = true } flag.should == false # The code in the lambda is still suspended; # it hasn't done any work. x.call # Now we ran the suspended function. flag.should == true 

Pay attention to two things:

  • I got the object from the lambda keyword. You also get this object, but since you do not assign it to a variable, it is immediately lost .;)
  • I used the call method to actually execute the code in the suspension (i.e. in lambda). In your example, you are not actually doing your git:checkout !

begin ... rescue ... end is a completely different mechanism: the goal is to correctly handle (or, in your case, swallow) exceptions. Stick to this form; this is the only one who does what you need. :)

+5
source

All Articles