2

I have a method as follows:

def something(param)
  case param
  when 1
    break if <already executed for some similar data>
    #Some code
  when 2
    #Some code
  else
    #Some code
  end
end

If param is 1, I will create a record in DB. In such case, I need to check that the same data are not present already, and if so, I need to break out of when.

When I try break if <condition>, I get this error:

Can't escape from eval with break

As a solution, I can change param's value before the case statement so that it (when 1) never meets the condition:

def something(param)
  param = 0 if <condition>
  case param
  when 1
    .
    .

but I feel it's ugly.

break is used to break out of loops, but I need an equivalent of it here that works like switch statement` break.

a = 1
b = 1

case a
when 1
  return if b == 1
  p "Code Executed"
end

gives me:

LocalJumpError: unexpected return
sawa
  • 165,429
  • 45
  • 277
  • 381
Abhi
  • 4,123
  • 6
  • 45
  • 77

1 Answers1

2

If that is all you have in the method body, then just do return instead of break.

If you cannot do that, then do:

when 1
  unless <already executed for some similar data>
    #Some code
  end
when 2
...
sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    @Abhi To use `return` you'll have to be inside a method body. In your edit, it's not inside a method, that's why it's throwing `LocalJumpError`. – Babar Al-Amin Mar 17 '16 at 05:53