Ne Nenne Ne Nenne - 6 months ago 11
Ruby Question

How to make Lambda (or lambda-like object) to call itself with a new parameter it got (Ruby)

I am within a method and want a simple solution to check client's response.

l=lambda { |answer|
if answer == 1
x*5
elsif answer == 2
x*10
elsif
puts "Please enter 1 or 2"
answer = gets.chomp
l.call(answer)
end
}


Obviously this code doesn't work, since lambda can't "see" itself, but is there a way to achieve the desired effect in a simple-fashioned way?

Because right now I'm just writing a new method to call and passing bunch of parameters, which I wouldn't need to if I were able to check the answers within the current method.

Answer

Slightly confused, is this what you're trying to achieve? I notice you have variable x, but this isn't referred anywhere (just answer is).

lam = ->(x) do
  x = Integer(x)

  case x
  when 1
    x * 5
  when 2
    x * 10
  else
    puts 'Please enter 1 or 2'
    input = gets.chomp
    lam.call(input)
  end
end

# 2.2.2 > lam.call(5)
# Please enter 1 or 2
# 3
# Please enter 1 or 2
# 2
#  => 20
# 2.2.2 > lam.call(1)
#  => 5