ruby do and the case of dear aunt sally

Ruby thinks ruby snacks take precedence over saving the gang

My first experience with “prettifying” code came with finding that there are many methods for which I first learned to pass a block via the “do…end” construction that can often be presented more cleanly using the “bracket” construction. A “do…end” example:

array = [1, 2, 3, 4]
array.map do |num|
num += 1
end
=> [2, 3, 4, 5]

And a “bracket” example:

array = [1, 2, 3, 4]
array.map {|num| num += 1}
=> [2, 3, 4, 5]

These examples do the exact same thing. Why use one over the other?

One reason is style and concision. When you have many lines of code, it can be more efficient and clean to present an operation on a single line. The balancing force is readability. Especially for operations that are more complex than simply increasing the value of an array of integers, it can be difficult to understand what a particular line of code is doing when it is very concise. It’s like sitting down to read prose and finding poetry on the page instead. Sort of.

The general rule of thumb seems to be “make it nice, but make it readable.” Find a balance between the two.

But, I discovered that there is another consideration. Just like the “order of operations” in math, Ruby has something called “precedence.” They’re the same thing. In fact, there’s quite a lot of overlap.

5 + 3 * 8
=> 29

Ruby does not necessarily read lines of code from left to right. It performs multiplication before addition unless you tell it otherwise.

(5 + 3) * 8
=> 64

The old PEMDAS mnemonic device might percolate back up from primary school. Please Excuse My Dear Aunt Sally. Parentheses, Exponents, Multiplication, Division, Addition, Subtraction. Ruby uses this same order in evaluating lines of code. And….many more.

Anyway, long story short, the “bracket” method has a higher order of precedence than the “do…end” method due to it use of brackets. There are situations where this fact could result in bugs, so this is worth being aware and careful of.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.