rubylambdaconditional-operator

Ternary operator not working inside Lambda function Ruby


I am trying to write a Lambda function in Ruby, to calculate the nth Fibonacci number.

fib = -> (n) { n in [1, 2] ? 1 : fib.[n - 1] + fib.[n - 2] }

This gives me the error,

./fib.rb:3: warning: One-line pattern matching is experimental, and the behavior may change in future versions of Ruby!
./fib.rb:3: syntax error, unexpected '?', expecting '}'
fib = -> (n) { n in [1, 2] ? 1 : fib.[n - 1] + fib.[n - 2...
./fib.rb:3: syntax error, unexpected ']', expecting '}'
...{ n in [1, 2] ? 1 : fib.[n - 1] + fib.[n - 2] }
./fib.rb:3: syntax error, unexpected ']', expecting '}'
...? 1 : fib.[n - 1] + fib.[n - 2] }

I assume the warning is because of the usage of the in syntax. But the rest, I cannot understand the error, why is the ternary operator not working?


I have already checked the question, How to write a conditional lambda in Ruby?, and I tried following it, but it gives me a different error instead.

fib = -> (n) { (n in [1, 2]) ? 1 : fib.[n - 1] + fib.[n - 2] }
./fib.rb:3: warning: One-line pattern matching is experimental, and the behavior may change in future versions of Ruby!
./fib.rb:3: syntax error, unexpected '['
...(n) { (n in [1, 2]) ? 1 : fib.[n - 1] + fib.[n - 2] }
./fib.rb:3: syntax error, unexpected ']', expecting '}'
...(n in [1, 2]) ? 1 : fib.[n - 1] + fib.[n - 2] }
./fib.rb:3: syntax error, unexpected ']', expecting '}'
...? 1 : fib.[n - 1] + fib.[n - 2] }

Solution

  • The in operator in Ruby does not do what you think it does. It's part of pattern matching in Ruby. To check if an array contains an element, use the .include? method.

    The syntax to call a lambda is also incorrect - either use dot with parentheses or square brackets without the dot.

    fib = -> (n) { [1, 2].include?(n) ? 1 : fib[n - 1] + fib[n - 2] }
    p fib[10]
    

    Output:

    55