Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda in Ruby 1.9

Tags:

ruby

I am not following this change. From:

longest_path_first = lambda do |host, location, _, _|

To:

longest_path_first = lambda do |(host, location, _, _)|

Can someone explain?

like image 409
Nick Vanderbilt Avatar asked Feb 25 '23 15:02

Nick Vanderbilt


1 Answers

>> al = lambda { |a,b,c| b }
>> bl = lambda { |(a,b,c)| b }
>> list = [[1,1,1], [2,2,2], [3,3,3], [4,0,4]]
>> list.sort_by &al
ArgumentError: wrong number of arguments (1 for 3)
    from (irb):1:in `block in irb_binding'
    from (irb):4:in `each'
    from (irb):4:in `sort_by'
>> list.sort_by &bl
 => [[4, 0, 4], [1, 1, 1], [2, 2, 2], [3, 3, 3]] 

Kind of illustrates why they've done it.

The reason of the change in Ruby is that they are trying to make lambdas consistent with normal methods:

>> def test(a,b,c); b; end
>> test [1,2,3]
ArgumentError: wrong number of arguments (1 for 3)
    from (irb):16:in `test'

A good way to get around the not exactly pretty syntax is to use the new and shiny Stab operator tm:

cl = ->(a, b, c) { b }
like image 137
Jakub Hampl Avatar answered Mar 08 '23 03:03

Jakub Hampl