Calling/applying lambda vs. function call - the syntax in Ruby is different. Why?

前端 未结 3 622
囚心锁ツ
囚心锁ツ 2021-02-01 03:15

I am kinda new to Ruby and still trying to understand some of the language design principles. IF I\'ve got it right, the lambda expression call in Ruby must be with square brace

3条回答
  •  情话喂你
    2021-02-01 03:22

    Regular Ruby method calls use () not curly braces which are for blocks. If you don't like [] for calling a lambda, you can always use the call method.

    Example:

    >> by_two = lambda { |x| x * 2 } #=> #
    >> by_two[5] #=> 10
    >> by_two.call(5) #=> 10
    

    Edit

    In newer version of Ruby also:

    >> by_two.(5) #=> 10
    

    As to why you can't just do by_two(5), when Ruby sees a bareword it first tries to resolve it as a local variable and if that fails as a method.

提交回复
热议问题