Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent for `break` in ruby's case / when statements?

Tags:

ruby

I'm looking for a statement that skips the execution of the when block, similiar to break for loops. Is this possible?

What I want to avoid is a construct like:

case n
  when 1
    if valid
      foo.bar
    end
  when 2
    if valid
      foo.foo
  end

The more desirable code block would look like:

case n
  when 1
    break unless valid
    foo.bar
  when 2
    break unless valid
    foo.foo
  end

Obviously, break does not work.

like image 946
nTraum Avatar asked Feb 19 '23 15:02

nTraum


2 Answers

Equivalent but more succinct:

case n
  when 1
    foo.bar if valid
  when 2
    foo.foo if valid
  end
end

of if the condition really applies to all cases, you can check it beforehand:

if valid
  case n
    when 1
      foo.bar
    when 2
      foo.foo
    end
  end
end

If neither works for you, then short answer: No, there's no break equivalent in a case statement in ruby.

like image 72
Thilo Avatar answered Feb 27 '23 02:02

Thilo


I'm always a fan of adding conditionals to the end of ruby statements. It makes for easier and more readable code. Which is what ruby is known for. My answer to your question would look something like this:

case n
when 1
    foo.bar
when 2
    bar.foo
end unless !valid
like image 29
jebentier Avatar answered Feb 27 '23 02:02

jebentier