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

前端 未结 3 621
囚心锁ツ
囚心锁ツ 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:45

    Because in Ruby, methods are not lambdas (like, for example, in JavaScript).

    Methods always belong to objects, can be inherited (by sub-classing or mixins), can be overwritten in an object's eigenclass and can be given a block (which is a lambda). They have their own scope for variables. Example method definition:

    a = :some_variable
    def some_method
      # do something, but not possible to access local variable a
    end
    
    # call with:
    some_method
    

    However lambdas/procs are plain closures, maybe stored in a variable - nothing else:

    a = :some_variable
    some_lambda = lambda{
      # do something, access local variable a if you want to
    }
    
    # call with:
    some_lambda[]
    

    Ruby combines both approaches with a powerful syntax, for example, passing blocks:

    def some_method_with_block(a)
      # do something, call given block (which is a lambda) with:
      yield(a) ? 42 : 21
    end
    
    # example call:
    some_method_with_block(1) do |x|
      x.odd?
    end #=> 42
    

提交回复
热议问题