programmer321 programmer321 - 21 days ago 8
Ruby Question

In Ruby, what is the return value in a loop?

Using the following code:

def get_action
action = nil
until Guide::Config.actions.include?(action)
puts "Actions: " + Guide::Config.actions.join(", ")
print "> "
user_response = gets.chomp
action = user_response.downcase.strip
end
return action
end


The following code takes the user response, and eventually returns its actions to another method.

I know that a loop repeats itself until its ultimately broken, but was curious about the return value, so I could better structure the loop for next time. In the
until
loop, I am curious to know whether what value does the
until
loop return, if there is a return value at all?

Answer

the return of a loop (loop, while, until, etc) can be anything you send to break

def get_action
  loop do
    action = gets.chomp
    break action if Guide::Config.actions.include?(action)
  end
end

or

def get_action
  while action = gets.chomp
    break action if Guide::Config.actions.include?(action)
  end
end

or you can use begin .. while

def get_action
  begin
    action = gets.chomp
  end while Guide::Config.actions.include?(action)
  action
end

or even shorter

def get_action
  action = gets.chomp while Guide::Config.actions.include?(action)
  action
end

PS: loops themselves return nil as a result (implicit break which is break nil) unless you use explicit break "something". If you want to assign result of the loop you should use break for this: x = loop do break 1; end

Comments