3

I'm not sure if subroutine is the right word. But I was wondering if you can do chunks of code that you can jump back and forth from?

For example if I wanted to have a program that has 3 blocks of code

Block1
Block2
Block3

And within Block1 it says

if something == 1
 go to Block2
end

Is this possible?

Thanks!

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
Westrock
  • 169
  • 4
  • 14

3 Answers3

3

Ruby doesn't have "goto". Normal practice is to use methods (subroutines):

def block1
  puts "foo"
end

def block2
  puts "bar"
end

if something == 1
  block1
  block2
end

# => foo
# => bar

One common reason to desire "goto" is to implement a state engine. In Ruby, small state engines are easily created using a simple case statement:

state = :init
loop do
  case state
  when :init
    puts "init"
    state = :working
  when :working
    puts "working"
    state = :done
  when :done
    puts "done"
    break
  end
end

# => init
# => working
# => done
Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
  • Thank you, both examples give me something to start with. – Westrock Oct 13 '12 at 00:01
  • Also important to note that the "def" has to be created before you call it. Can't call block1 before you have created a def block1. Or at least thats what happened to me in testing. – Westrock Oct 13 '12 at 03:27
2

You could recompile Ruby with -DSUPPORT_JOKE (cf. this post), but I would not recommend it ;-)

See also this question: goto command in Ruby?

Community
  • 1
  • 1
DMKE
  • 4,553
  • 1
  • 31
  • 50
1

Well, in Ruby, subroutines are just implemented as blocks or methods, which are close to blocks bound to an object. But, jumping to and fro you say, you might be talking not about subroutines, but COroutines. These, in Ruby, are represented by Fibers.

Boris Stitnicky
  • 12,444
  • 5
  • 57
  • 74