c = 5
until c == 0 do
print c
c -= 1
end
/break
c = 5
until c == 0
print c
c -= 1
end
What's the difference?
Both of them display 54321 as output.
do is optional. It indicates the beginning of the block of code to be repeatedly executed.
In your example it makes no difference. However if you try re-writing the code in one line, you can see why its needed:
c = 5
until c == 0 do print c; c -= 1 end
# 54321 => nil
Now try this without do:
c = 5
until c == 0 print c; c -= 1 end
# SyntaxError: (irb):115: syntax error, unexpected tIDENTIFIER, expecting keyword_do_cond or ';' or '\n'
As you can see there is no clear beginning for block, Ruby will throw a SyntaxError.
There is no difference between until and until do. Do is optional and both will show same output. If want to get some more idea about this while and while do
There is absolutely no difference. It is like the while [condition] [block] end vs while [condition] do [block] end or if [condition] [block] end vs if [condition] then [block] end.
In Ruby, often there are tons of ways of doing the same thing - the important is to be consistent, either way.
Related
How can i do stuff like that in ruby:
# => ANCHOR GO BACK HERE
...some code
f = 0
while f == 0
... some code
f = 1
end
# if [condition] => ANCHOR FROM HERE
It's sth like goto in pascal i belive, but i'm not sure.
I want to go back to the "Anchor" in code when certain condition happen.
Could somebody help me with that?
One way to do this is with a loop:
loop do
# ...some code
f = 0
while f == 0
... some code
f = 1
end
break unless some_condition
end
So, the loop will continue unless the condition is met.
I'm practicing the While Loop in Ruby and got a basic example as below
i = 3
while i > 0 do
print i
i -= 1
end
My question is why I can't interchange do..end with {} as if I rewrite the above code as below it doesn't work anymore
i = 3
while i > 0 {
print i
i -= 1
}
However, it seems to work without the first "do"
i = 3
while i > 0
print i
i -= 1
end
Could anyone explain the rule or redirect me to the right resource? Thx!
As you said do is optional for while loop. While keyword is enough to define a block which is finished with end like any other block in ruby. In addition, end is mandatory for while block.
If you want to use while on just one line you can do such as below:
i = 0
i += 1 while i < 10
While mandatory needs end in Ruby.
Syntax example
do is optional and can be omitted.
So, it is not the case where pair do - end can be replaced with {}
I have a piece of code in Ruby which goes as follows:
def check
if a == b || c == b
# execute some code
# b = the same variable
end
end
can this be written like
def check
if a || c == b
# this doesn't do the trick
end
if (a || c) == b
# this also doesn't do the magic as I thought it would
end
end
Or in a manner where I don't need to type b twice. This is out of laziness and I would like to know.
if [a, c].include? b
# code
end
This is, however, significantly slower than the code you want to avoid -- at least as long as a, b and c are basic data. My measurements showed a factor of 3. This is probably due to the additional Array object creation. So you might have to weigh DRY against performance here. Normally it should not matter, though, because both variants do not take long.
While not an exact equivalent of a == b || a == c, case statement offers syntax for this:
case a
when b, c then puts "It's b or c."
else puts "It's something else."
end
Feel free to opent the nearest Ruby textbook and read about how case statement works. Spoiler: It works by calling #=== method on the compared objects:
a = 42
b, c = Object.new, Object.new
def b.=== other; puts "b#=== called" end
def c.=== other; puts "c#=== called" end
Now run
case a
when b, c then true
else false end
This gives you a lot of flexibility. It requires work in the back office, but after you do it, looks like magic in the front office.
You should really know why this doesn't work:
(a || c) == b
This seems like a translation of the sentence "a or c is equal b", which makes sense in English.
In almost all programming languages, (a || c) is an expression, whose evaluated result will be compared to b. The translation to English is "The result of the operation "a or c" is equal to b".
#undur_gongor's answer is perfectly correct. Just to add though, if you're working with arrays, for example:
a = [1,2,3]
c = [4,5,6]
b = [5,6]
if [a, c].include? b
# won't work if your desired result is true
end
You'd have to do something like:
if [a,c].any?{ |i| (i&b).length == b.length }
# assuming that you're always working with arrays
end
# otherwise ..
if [a,c].any?{ |i| ([i].flatten&[b].flatten).length == [b].flatten.length }
# this'll handle objects other than arrays too.
end
What about this?
if [a,c].index(b) != nil;puts "b = a or b = c";end
Acolyte pointed out you can use b == (a||c), you just had it backwards, but that only works for the left value, since (a||c) is always a, assuming a isn't falsey.
Another option is to use a ternary operator.
a==b ? true : b==c
I'm not sure of the speed difference cited wrt the array approach, but I would think this could be faster since it's doing either one or two comparisons and doesn't need to deal with arrays. Also, I assume it's the exact same as (a==b || b==c), but it's a stylistic alternative.
How to break double statement?
a = 1
b = 2
c = 3
if a == 1
if b == 2
c = 5
d = 6
break
end
end
puts c
puts d
Output
loop.rb:9: Invalid break
loop.rb: compile error (SyntaxError)
You can't break from inside an if, you can only break from inside loops and blocks.
If what you're asking is how to break from two nested loops, you can use catch in combination with throw—these are not the same as try and catch in other languages.
catch(:stop) do
while some_cond
while other_cond
throw :stop
end
end
end
Of course, you can always just set a flag or some such to tell the outer loop that it should break too.
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?
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.
I found the following snippet while reading the source for Tempfile#initialize in the Ruby core library:
begin
tmpname = File.join(tmpdir, make_tmpname(basename, n))
lock = tmpname + '.lock'
n += 1
end while ##cleanlist.include?(tmpname) or
File.exist?(lock) or File.exist?(tmpname)
At first glance, I assumed the while modifier would be evaluated before the contents of begin...end, but that is not the case. Observe:
>> begin
?> puts "do {} while ()"
>> end while false
do {} while ()
=> nil
As you would expect, the loop will continue to execute while the modifier is true.
>> n = 3
=> 3
>> begin
?> puts n
>> n -= 1
>> end while n > 0
3
2
1
=> nil
While I would be happy to never see this idiom again, begin...end is quite powerful. The following is a common idiom to memoize a one-liner method with no params:
def expensive
#expensive ||= 2 + 2
end
Here is an ugly, but quick way to memoize something more complex:
def expensive
#expensive ||=
begin
n = 99
buf = ""
begin
buf << "#{n} bottles of beer on the wall\n"
# ...
n -= 1
end while n > 0
buf << "no more bottles of beer"
end
end
Originally written by Jeremy Voorhis. The content has been copied here because it seems to have been taken down from the originating site. Copies can also be found in the Web Archive and at Ruby Buzz Forum. -Bill the Lizard
Like this:
people = []
begin
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end while not info.empty?
Reference: Ruby's Hidden do {} while () Loop
How about this?
people = []
until (info = gets.chomp).empty?
people += [Person.new(info)]
end
Here's the full text article from hubbardr's dead link to my blog.
I found the following snippet while reading the source for Tempfile#initialize in the Ruby core library:
begin
tmpname = File.join(tmpdir, make_tmpname(basename, n))
lock = tmpname + '.lock'
n += 1
end while ##cleanlist.include?(tmpname) or
File.exist?(lock) or File.exist?(tmpname)
At first glance, I assumed the while modifier would be evaluated before the contents of begin...end, but that is not the case. Observe:
>> begin
?> puts "do {} while ()"
>> end while false
do {} while ()
=> nil
As you would expect, the loop will continue to execute while the modifier is true.
>> n = 3
=> 3
>> begin
?> puts n
>> n -= 1
>> end while n > 0
3
2
1
=> nil
While I would be happy to never see this idiom again, begin...end is quite powerful. The following is a common idiom to memoize a one-liner method with no params:
def expensive
#expensive ||= 2 + 2
end
Here is an ugly, but quick way to memoize something more complex:
def expensive
#expensive ||=
begin
n = 99
buf = ""
begin
buf << "#{n} bottles of beer on the wall\n"
# ...
n -= 1
end while n > 0
buf << "no more bottles of beer"
end
end
This works correctly now:
begin
# statment
end until <condition>
But, it may be remove in the future, because the begin statement is counterintuitive. See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745
Matz (Ruby’s Creator) recommended doing it this way:
loop do
# ...
break if <condition>
end
From what I gather, Matz does not like the construct
begin
<multiple_lines_of_code>
end while <cond>
because, it's semantics is different than
<single_line_of_code> while <cond>
in that the first construct executes the code first before checking the condition,
and the second construct tests the condition first before it executes the code (if ever). I take it Matz prefers to keep the second construct because it matches one line construct of if statements.
I never liked the second construct even for if statements. In all other cases, the computer
executes code left-to-right (eg. || and &&) top-to-bottom. Humans read code left-to-right
top-to-bottom.
I suggest the following constructs instead:
if <cond> then <one_line_code> # matches case-when-then statement
while <cond> then <one_line_code>
<one_line_code> while <cond>
begin <multiple_line_code> end while <cond> # or something similar but left-to-right
I don't know if those suggestions will parse with the rest of the language. But in any case
I prefere keeping left-to-right execution as well as language consistency.
a = 1
while true
puts a
a += 1
break if a > 10
end
Here's another one:
people = []
1.times do
info = gets.chomp
unless info.empty?
people += [Person.new(info)]
redo
end
end
ppl = []
while (input=gets.chomp)
if !input.empty?
ppl << input
else
p ppl; puts "Goodbye"; break
end
end