Does begin . . . end while denote a 'block'?
Block has a special meaning in Ruby. According to Matz, Ruby's creator, you can look at a block as a nameless function - typically something that can be yield
ed into, and which may also take parameters.
You may see the following kind of disamiguation when describing Ruby syntax:
begin
...end
(what is called block in other languages) may sometimes be referred to simply as what it is, i.e. an expression (which may in turn contain other expressions - an expression is simply something that has a return value) in Ruby. Some references will still call it abegin/end block
, or acode block
, adding somewhat to the confusiondo
...end
or{...}
will always be referred to as a block in Ruby
For examples, peruse the the Ruby syntax man page, e.g.
begin
expression
end
expression
while
expression
loop
block
For further reading, see:
- Programming Ruby
- Ruby (from other languages)
- Much, much more documentation
What is use of ||= begin....end block in Ruby?
First of all, you need to be aware that a defined method inherently includes the functionality of a begin ... end
block.
In the context of exception handling, def method_name ... end
is functionally equivalent to begin ... end
. Both can include rescue
statements for example.
The two blocks of code you have shared are actually identical, and there is no benefit in one over the other ... unless your method
is needed in more than one place. In that case, you DRY up your code by putting the logic into a single method and calling it from multiple other places.
Use of Begin / End Blocks and the Go keyword in SQL Server?
GO is like the end of a script.
You could have multiple CREATE TABLE statements, separated by GO. It's a way of isolating one part of the script from another, but submitting it all in one block.
BEGIN and END are just like { and } in C/++/#, Java, etc.
They bound a logical block of code. I tend to use BEGIN and END at the start and end of a stored procedure, but it's not strictly necessary there. Where it IS necessary is for loops, and IF statements, etc, where you need more then one step...
IF EXISTS (SELECT * FROM my_table WHERE id = @id)
BEGIN
INSERT INTO Log SELECT @id, 'deleted'
DELETE my_table WHERE id = @id
END
Naming: BEGIN ~ END vs LIVE ~ EVIL block structured languages
As a pun on "reversed" I suggest: IF ~ FI, DO ~ OD, CASE ~ IN ~ OUT ~ ESAC as "reverent" block structuring.
The first case of "reverent" block structuring might be found in http://ALGOL Bulletin - ISSN: 0084-6198, however I cannot find the originators name or an exact posting.
Hence also: BEGIN ~ END, DO ~ END, IF ~ END IF as "irreverent" block structuring.
An example of a technical palindrome that appears much earlier (and outside of computing) would be Lord Kelvin's Mho (℧).
What does Ruby's BEGIN do?
BEGIN
and END
set up blocks that are called before anything else gets executed, or after everything else, just before the interpreter quits.
For instance, running this:
END { puts 'END block' }
puts 'foobar'
BEGIN { puts 'BEGIN block' }
Outputs:
BEGIN block
foobar
END block
Normally we'd use a bit more logical order for the BEGIN
and END
blocks, but that demonstrates what they do.
Does a begin-end block affect the performance of a conditional statement?
No, there is no difference in performance, the code created will be identical.
An aspect that might be more important than that the second option looks nicer, is that it is better for maintainence. If you need to add another statement in the else block, you will not accidentally forget to add the begin and end, which would put the statement outside the if and always be executed.
SQL Server BEGIN/END vs BEGIN TRANS/COMMIT/ROLLBACK
BEGIN and END deal with code blocks. They are similar to the curly braces you see in many languages:
if (somethingIsTrue)
{ // like BEGIN
// do something here
} // like END
In SQL, this is:
if somethingIsTrue
BEGIN
-- do something here
END
BEGIN TRAN
, COMMIT
, and ROLLBACK
begin and end transactions. They do not specify a new block of code; they only mark the transaction boundaries.
Note that you can write a BEGIN TRAN
and COMMIT
in separate blocks of code. For example, if you want code to be part of a transaction, but you don't want to start a new one if the code is already in a transaction, you can do something like this:
declare @TranStarted bit = 0
if @@trancount = 0
begin
set @TranStarted = 1
begin tran
end
-- ... do work ...
if @TranStarted = 1
begin
commit
set @TranStarted = 0
end
Any harm in using BEGIN / END to organize SQL code?
You can do this. It's a good idea to structure code like that because it's integrated with the language and the IDE in a way that comments are not. In C languages I sometimes use {}
blocks for that in case it is necessary to have larger methods.
I found the col/line style easier to read for me
If that's easier for you then it makes sense. But maybe it also makes sense to train your eyes to accept a style where many columns are in one line. This saves a tremendous amount of vertical space. More fits on the same screen and clarity increases.
Does Ruby have a built-in do ... while?
...The best I could come up with is the loop
construct with a break
at the end:
loop do
...
break unless condition
end
Why does python use 'else' after for and while loops?
It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:
found_obj = None
for obj in objects:
if obj.key == search_key:
found_obj = obj
break
else:
print('No object found.')
But anytime you see this construct, a better alternative is to either encapsulate the search in a function:
def find_obj(search_key):
for obj in objects:
if obj.key == search_key:
return obj
Or use a list comprehension:
matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
print('Found {}'.format(matching_objs[0]))
else:
print('No object found.')
It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.
See also [Python-ideas] Summary of for...else threads
Related Topics
Has Anyone Figured Out a Way to Run the Same Cucumber Scenario on Multiple Browsers/Web Drivers
How to Get a Substring from Position N to the Last Char in Ruby
After Installing a Gem Within a Script, How to Load the Gem
How to Integrate Hoptoad with Delayedjob and Daemonspawn
Architecture for a Modular, Component-Based Sinatra Application
Chef and Erb Templates. How to Use Boolean Code Blocks
C1 or C2 Coverage Tool for Ruby
Ruby on Rails Model Inside Namespace Can't Be Found in Controller
Initializing Instance Variables in Mixins
Rails 12 Hour Am/Pm Range for a Day