简体   繁体   中英

Ruby substitute for goto

How can I do something like this in Ruby?

if variable = something  
    do A  
    do B  
    do D  
elsif variable = something different
    do A
    do B
    do C
    do D
else
    do A
    do C
    do D

A = set of loops with if else
B = set of loops with if else
C = set of loops with if else
D = final steps

Looking for a way to accomplish something like this in Ruby. I'm sure this question is answered somewhere but I don't know what it would be called. I found some information about a gem that allows you to use goto but I would prefer to learn the correct way to do this (also it seems that this might be a joke). I'd prefer to write the code out myself but I can put my actual code up if that helps answer my question.

If someone could just point me in the right direction.

Also if goto isn't a joke why is it not okay to use?

Instead of goto just create functions for A, B and so on and use them

for example:

def A
  # Lot of code
end

Now you can goto A by just writing A .

Also instead of using if/else you can use switch case, so that your code will look like

A
case variable
when something
  B
  D
when something else
  B
  C
  D
else
  C
  D
end

This is a classic use for switch case. Here is how you do it in ruby. Also, I would make all the do's methods and call them from inside when

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM