Sobes.tech
Middle

Mis on lambda ja protseduur Ruby's?

sobes.tech AI

Vastus AI-lt

Lambda and procedure in Ruby are Proc objects that encapsulate blocks of code.

The main differences lie in their behavior regarding return values and the number of arguments accepted:

  • Lambda:

    • Strictly controls the number of arguments (like a regular method).
    • Inside a lambda, return only returns from the lambda itself.
    # Lambda example
    lambda_proc = lambda { |a, b| return a + b }
    puts lambda_proc.call(1, 2) # 3
    
    # Error: incorrect number of arguments
    # lambda_proc.call(1)
    
  • Proc:

    • Less strict about the number of arguments (may not raise an error if more or fewer arguments are provided).
    • Inside a proc, return returns from the context where the proc was defined (like in a block).
    # Proc example
    proc_proc = Proc.new { |a, b| return a + b }
    
    def method_with_proc
      proc_proc = Proc.new { return "return from method" }
      proc_proc.call
      "this text will not be shown"
    end
    
    puts method_with_proc # return from method
    
    # Does not raise an error with incorrect argument count (behavior may be unpredictable)
    # proc_proc.call(1)
    

Comparison:

Characteristic Lambda Proc
Argument control Strict Not strict
return behavior Returns from itself Returns from the context
Class Proc (but with lambda?) Proc
Creation lambda { ... }, -> { ... } Proc.new { ... }, proc { ... }

In most cases, it is preferable to use lambdas for passing blocks of behavior similar to methods, due to their more predictable behavior with arguments and return. Procs are often used for lower-level tasks or when their specific return behavior is desired.