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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With