daremkd
daremkd

Reputation: 8424

Lambdas and only 1 argument in case statements in Ruby

As I get it, you can use a proc/lambda inside, switch, for example:

is_even = ->(x) { x % 2 == 0 }

case number
when 0 then puts 'zero'
when is_even then puts 'even'
else puts 'odd'
end

As I understand it, and from the examples I see, is it that lambdas can be used in case statements ONLY IF they accept only 1 parameter, since you can't do a case statement with more than 1 argument (case a, b isn't possible, except if maybe these elements are enclosed into an array). So basically if you try to use a lambda with more than 1 parameter in a case statement the code is going to break. Correct me if I'm wrong.

Upvotes: 1

Views: 366

Answers (1)

Darek Nędza
Darek Nędza

Reputation: 1420

It's because:

is_even = ->(x) { x % 2 == 0 }
is_even.lambda? #true

is "lambda" ( is_even = lambda(x) { x % 2 == 0 } is equivalent of above code)

There exist procs:

is_even = proc{|x| x % 2 == 0 } # Proc.new{|x| x % 2 == 0 }
is_even.lambda? #false

lambdas checks for number of arguments. procs on other hand doesn't check number of arguments.

ppp1 = Proc.new{|x| x % 2 == 0 } #=> #<Proc:0x507f300@(pry):152>
ppp1.call(2,3,4,5) #true

ppp2 = ->(x){ x % 2 == 0 } # => #<Proc:0x2c5ac40@(pry):158 (lambda)>
ppp2.(2,4) # ArgumentError: wrong number of arguments (2 for 1)

You can read more here.

Upvotes: 2

Related Questions