hockmode
hockmode

Reputation: 57

How to write a case statement in Ruby with multiple statements inside a when clause?

I tried separating the statements inside the when clauses with commas but it didn't work.

when 1; statement, statement, statement

when 2; statement, statement, statement

I couldn't find any examples of this online.

case selection
when 1
  system "clear"
  view_all_entries
  main_menu
when 2
  system "clear"
  create_entry
  main_menu
when 3
  system "clear"
  search_entries
  main_menu
when 5
  puts "Good bye!"
  exit(0)
else
  system "clear"
  puts "Sorry, that is not a valid input"
  main_menu
end

Upvotes: 2

Views: 12687

Answers (4)

AnoE
AnoE

Reputation: 8345

Your question seems to be "how can I put all those statements on one line to have fewer lines".

Generally, you can use ";" in ruby to replace the End-of-Lines. Thus:

case selection
when 1; system "clear"; view_all_entries; main_menu
...

Or

case selection
when 1 then system "clear"; view_all_entries; main_menu
...

Using the ";" in any way is very much not ruby-like and not recommended. See below (other answers) for a much nicer refactoring which strips the duplicated code.

Upvotes: 13

Cary Swoveland
Cary Swoveland

Reputation: 110685

I would be inclined to write it thusly:

if selection==5
  puts "Good bye!"
  exit(0)
end

system "clear"

case selection
when 1 then view_all_entries
when 2 then create_entry
when 3 then search_entries
else        puts "Sorry, that is not a valid input"
end

main_menu

Upvotes: 9

ndnenkov
ndnenkov

Reputation: 36100

You can use the when - then syntax. Note that it is considered bad practice if the lines become too long:

case value
when 1 then statement1
when 2 then statement2
when 3 then statement3
when 4 then statement4
end

To execute multiple statements for the same condition on the same line you can separate them with ;. However, this is always considered a bad practice:

case value
when 1 then statement1; statement11; statement12
when 2 then statement2; statement21; statement22
when 3 then statement3; statement31; statement32
when 4 then statement4; statement41; statement42
end

Upvotes: 5

zetetic
zetetic

Reputation: 47548

i've tried comma, it does not work

Yes, it does:

case value
when 1, 2
  "one or two"
else
  "something other than one or two"
end

returns "one or two" if value is 1 or 2

Upvotes: 4

Related Questions