How to write a switch statement in Ruby

2018-12-31 23:16发布

How do I write a switch statement in Ruby?

21条回答
浅入江南
2楼-- · 2019-01-01 00:00

You can do like this in more natural way,

case expression
when condtion1
   function
when condition2
   function
else
   function
end
查看更多
时光乱了年华
3楼-- · 2019-01-01 00:01

It's called case and it works like you would expect, plus lots more fun stuff courtesy of === which implements the tests.

case 5
  when 5
    puts 'yes'
  else
    puts 'else'
end

Now for some fun:

case 5 # every selector below would fire (if first)
  when 3..7    # OK, this is nice
  when 3,4,5,6 # also nice
  when Fixnum  # or
  when Integer # or
  when Numeric # or
  when Comparable # (?!) or
  when Object  # (duhh) or
  when Kernel  # (?!) or
  when BasicObject # (enough already)
    ...
end

And it turns out you can also replace an arbitrary if/else chain (that is, even if the tests don't involve a common variable) with case by leaving out the initial case parameter and just writing expressions where the first match is what you want.

case
  when x.nil?
    ...
  when (x.match /'^fn'/)
    ...
  when (x.include? 'substring')
    ...
  when x.gsub('o', 'z') == 'fnzrq'
    ...
  when Time.now.tuesday?
    ...
end
查看更多
听够珍惜
4楼-- · 2019-01-01 00:01

Depending on your case, you could prefer to use a hash of methods.

If there is a long list of when's and each of them has a concrete value to compare with (not an interval), it will be more effective to declare a hash of methods and then to call the relevant method from the hash like that.

# Define the hash
menu = {a: :menu1, b: :menu2, c: :menu2, d: :menu3}

# Define the methods
def menu1
  puts 'menu 1'
end

def menu2
  puts 'menu 2'
end

def menu3
  puts 'menu3'
end

# Let's say we case by selected_menu = :a
selected_menu = :a

# Then just call the relevant method from the hash
send(menu[selected_menu])
查看更多
登录 后发表回答