stackjlei
stackjlei

Reputation: 10035

What is the purpose of using ruby begin without rescue?

In looking at http://vaidehijoshi.github.io/blog/2015/08/25/unlocking-ruby-keywords-begin-end-ensure-rescue/ I don't understand the example

def create_or_update_batch
  @batch ||= begin
    BookBatch.create(book_batch.batch_attrs)
  end

  @batch.update
end

What if I had

def create_or_update_batch
  @batch ||= BookBatch.create(book_batch.batch_attrs)

  @batch.update
end

How is this different?

Upvotes: 0

Views: 501

Answers (1)

Konstantin Strukov
Konstantin Strukov

Reputation: 3019

This example is just bad - for the described case, there is no difference in behavior (and the bytecode will look very similar if not the same).

begin ... end block can be used for grouping several expressions - for example, for memoizing the intermediate result of some heavy calculations without additional intermediate assignments, like

some_var = begin
  # a bunch of expressions goes there
end

# continue calculations using some_var

Actually, begin ... end block acts in pretty much the same way as def ... end does to define a method. And because of this similarity begin .... end is not used very often in the production code - in most practical cases it's better to move the group of closely related expressions into a separate method.

There is one case when this block can make the difference - consider

some_method while false

vs

begin
  some_method
end while false

In the former snippet some_method isn't called at all, while in the latter it will be called once. But this usage is kind of discouraged - it makes the code trickier (the same can be done in a much more readable way with loop and explicit break)

Upvotes: 3

Related Questions