So as I transition from the world of C# to Ruby due to a change in employment (And that I have grown to hate C#), I’ve been spending time getting used to certain concepts I’ve used heavily in C# done in Ruby. One big one is the ability to pass anonymous methods into other methods. So something like this in C#:
public void LambdaHolder() { MethodThatUsesTheLambda(x => { Console.WriteLine(x +1)); } public void MethodThatUsesTheLambda(Action<int> passedInMethod) { foreach(var item in Enumerable.Range(0, 10) { passedInMethod(item); } }
When done in Ruby it looks like this:
def lambda_holder method_that_uses_the_lambda (lambda {|x| puts x +1}) end def method_that_uses_the_lambda (passed_in_method) (1...10).each &passed_in_method end
The main thing is the & character. This allows the each method to recognize passed_in_method as an expression it can call and pass an argument to. Essential the same as:
def method_that_uses_the_lambda (passed_in_method) (1...10).each {|x| passed_in_method.call(x)} end
Why would you want to do that? Readability if nothing else.
def method_that_uses_the_lambda (will_output_a_number) (1...10).each &will_output_a_number end
Compared to:
def method_that_uses_the_lambda (will_output_a_number) (1...10).each {|x| will_output_a_number.call(x)} end
Yeah… so there it is… I got nothin’ else… this is really awkward.