0

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.

  • Possible duplicate of [Can I reference a lambda from within itself using Ruby?](http://stackoverflow.com/questions/9516061/can-i-reference-a-lambda-from-within-itself-using-ruby) – anujm May 28 '16 at 22:06
  • I don't see how something like this could be useful, as `answer` never changes. The standard way of doing this is `loop do`, ; ; if answer is OK, calculate some `x` then `break x``; otherwise remain in the loop. – Cary Swoveland May 29 '16 at 04:41
  • Answer does change, why do you say that? Just a mistake in my code, it should be "else" instead of the last "elsif". –  May 29 '16 at 08:51

1 Answers1

1

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
Nabeel
  • 2,272
  • 1
  • 11
  • 14
  • Thanks, it seems just my syntax was bad. In my OP it should read 'else' instead of 'elsif', but that wasn't the original problem, since I just simplified the code to ask the question. When testing I was able to see the "else" part, but not call the lambda again with a new input, that's why I assumed lambda was not reachable within the lambda. It's not the case thankfully, the problem was with syntax in my code or something. As for non-referred x - well, as I said I'm in the method, so I have bunch of values which pass to lambda without referring. –  May 28 '16 at 22:46
  • Ah I see, glad it's sorted :). – Nabeel May 28 '16 at 22:49