You’re almost there. First of all, in Ruby, you don’t declare your
instance variables outside of methods. You just set them inside of a
method, and they get automatically declared. For example:
class Foo
def bar
@baz = 3
end
def qux
@quux = 4
end
def show_me
p @baz
p @quux
end
end
If you say:
a = Foo.new
a.show_me
It should print:
nil
nil
Because the object’s instance variables of @baz and @quux haven’t been
initialized. If you say:
a = Foo.new
a.bar
a.show_me
It should print:
3
nil
because when the bar method was called, it initialized the @baz
variable to 3. Likewise, if you say:
a = Foo.new
a.bar
a.qux
a.show_me
You will get:
3
4
Also, it looks like you want to use a while loop instead of a for
loop. So for your example, you could do this:
class MyFirstClass
def start_my_loop
while !@stop_loop
puts ‘Im inside the loop…’
end
end
def stop_my_loop
@stop_loop = true
end
end
Notice that when you call start_my_loop, if @stop_loop hasn’t yet been
initialized, its value is nil. This means that it will begin
executing the loop. If you wanted to explicitly set the value of
@stop_loop from the get-go, then use a constructor:
class MyFirstClass
def initialize
@stop_loop = false
end
def start_my_loop
while !@stop_loop
puts ‘Im inside the loop…’
end
end
def stop_my_loop
@stop_loop = true
end
end
So now you can use this code like this:
a = MyFirstClass.new
a.start_my_loop
a.stop_my_loop
However, this will not work. Once the program enters the loop, it
stays there. You need some way to pass control of the program to
outside of the loop, otherwise, you’ll be looping forever. One way to
do this is to use multiple threads. Another way is to use blocks,
like this:
class MyFirstClass
def start_my_loop
while yield
puts ‘Im inside the loop…’
end
end
end
a = MyFirstClass.new
a.start_my_loop do
if rand(5) == 3
false
else
true
end
end
Every time the program gets to the yield statement, it calls the block
that you passed to the start_my_loop method. This block randomly
returns true or false. If it returns true, the loop is executed
again.
I hope this was helpful!
Cheers,
Wyatt G.