Taken from Programming ruby 1.9 book:
def my_while(cond, &body)
while cond.call
body.call
end
end
a=0
my_while -> { a < 3 } do
puts a
a += 1
end
produces:
0
1
2
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The method expects an explicit parameter
cond, and this "condition" is assumed to be a lambda/proc (the assumption is made by relying oncond.callto succeed) and has to be passed to the methodmy_whileexplicitly. The&syntax captures a method’s block (if present) in a variable by implicitly converting it to aProcobject (see ‘The ampersand’).Blocks are not real objects in Ruby and thus have to be converted by using the ampersand syntax. Once the block is bound to a Proc, you can send the
callmessage on it as on any other proc/lambda.The
->syntax is short forlambda, which converts a block to a Proc object (explicitly). There is also a slight difference between using lambda and Proc.new. Again, the wikibook: