liveBook · Manning

Operator precedence

As explained in The Well-Grounded Rubyist, Fourth Edition

Precedence is the rule governing how Ruby groups syntactic constructs when multiple constructs could be associated with an expression or method call.

Operator precedence determines how Ruby groups expressions, method calls, and attached code blocks when more than one grouping is possible. section 6.3.4 section 6.1.1

Curly braces and do/end bind differently

Both `array.map { |n| n * 10 }` and `array.map do |n| n * 10 end` produce `[10, 20, 30]` when used alone. With `puts`, however, `puts array.map { |n| n * 10 }` attaches the block to `map`, while `puts array.map do |n| n * 10 end` attaches it to `puts`. The latter is effectively `puts(array.map) do |n| n * 10 end`; `map` receives no block and returns an enumerator, while `puts` ignores its block. section 6.3.4

Use precedence rules to read and write Ruby expressions carefully:

  • Treat curly-brace blocks as binding more tightly than do/end blocks when a surrounding method call could claim the block. section 6.3.4
  • Remember that `!` has higher precedence than `==`: `!x == 1` compares the negation of `x` with `1`, rather than negating the comparison. section 6.1.1
  • Prefer parentheses around negated comparisons, as in `!(x == 1)`, even when Ruby does not strictly require them. section 6.1.1
  • When a method seems to ignore a block, inspect precedence before assuming the method is broken; methods need not yield to supplied blocks. section 6.3.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains grouping through runnable contrasts and equivalent calls, but does not provide a complete precedence table.
Examples
Uses array mapping with puts and contrasts `!x == 1` with parenthesized negation.
What it assumes
Assumes familiarity with Ruby method calls, blocks, arrays, conditionals, and boolean expressions.
What you can do after
Diagnose/debug with it by checking block attachment, equivalent parenthesized calls, and negated comparison grouping.
How it connects
Connects block syntax, method calls, map, enumerators, conditional expressions, equality, and logical negation.

Also explained in

Compare how 7 books explain operator precedence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.