I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name):
people = [] info = 'a' # must fill variable with something, otherwise loop won't execute while not info.empty? info = gets.chomp people += [Person.new(info)] if not info.empty? end
This code would look much nicer in a do ... while loop:
people = [] do info = gets.chomp people += [Person.new(info)] if not info.empty? while not info.empty?
In this code I don't have to assign info to some random string.
Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?
The do keyword comes into play when defining an argument for a multi-line Ruby block. Ruby blocks are anonymous functions that are enclosed in a do-end statement or curly braces {} . Usually, they are enclosed in a do-end statement if the block spans through multiple lines and {} if it's a single line block.
Ruby while StatementExecutes code while conditional is true. A while loop's conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.
Which of the following is not a type of loop in ruby? Explanation: Foreach loop is not there in ruby.
CAUTION:
The begin <code> end while <condition>
is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop
, e.g.
loop do # some code here break if <condition> end
Here's an email exchange in 23 Nov 2005 where Matz states:
|> Don't use it please. I'm regretting this feature, and I'd like to |> remove it in the future if it's possible. | |I'm surprised. What do you regret about it? Because it's hard for users to tell begin <code> end while <cond> works differently from <code> while <cond>
RosettaCode wiki has a similar story:
During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.
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