Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

ruby

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?

like image 484
developer098 Avatar asked Nov 11 '16 22:11

developer098


People also ask

What does loop return in Ruby?

x do puts x - i end puts "Done!" The odd thing about the for loop is that the loop returns the collection of elements after it executes, whereas the earlier while loop examples return nil . Let's look at another example using an array instead of a range.

What does return do in for loop?

The return statement is useful because it saves time and makes the program run faster by returning the output of method without executing unnecessary code and loops. It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed.

What is the return value of a function in Ruby?

In Ruby, a method always return exactly one single thing (an object). The returned object can be anything, but a method can only return one thing, and it also always returns something. Every method always returns exactly one object.

What is the return type of for loop?

Java for-each Loop It returns element one by one in the defined variable. Syntax: for(data_type variable : array_name){ //code to be executed.


1 Answers

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

like image 86
fl00r Avatar answered Sep 19 '22 12:09

fl00r