开发者

Lambda in Ruby 1.9

开发者 https://www.devze.com 2023-02-21 08:41 出处:网络
I am not following this开发者_开发知识库 change. From: longest_path_first = lambda do |host, location, _, _|

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?


>> 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 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号