developer098
developer098

Reputation: 843

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?

Upvotes: 6

Views: 11358

Answers (2)

Rich
Rich

Reputation: 153

loop can also return a value without using a break

def loop_return
  @a = [1, 2, 3 ].to_enum
  loop do
    @a.next
  end
end

print loop_return  #=> [1, 2, 3]

Upvotes: 0

fl00r
fl00r

Reputation: 83680

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

Upvotes: 8

Related Questions