Nothing ventured, nothing gained

a blog by Marc Chung

Understanding operator precedence using ParseTree

»

by Marc Chung

From the ruby part of the brain.

A small tribute to Guy Decoux, an early Ruby programmer who once walked the Ruby parse tree to answer a simple operator precedence question posed by Matz.

Read Matz’s question and Guy’s answer. Today, we can answer the same question with the following code:

hoktauri$ cat guy.rb
if $0 == __FILE__
    require 'rubygems'
    require 'parse_tree'
    require 'parse_tree_extensions'
    require 'yaml'
    pt = ParseTree.new
    y pt.parse_tree_for_string("a b c, d")
end

hoktauri$ ruby guy.rb
- - -
- - :fcall
  - :a
  - - :array
    - - :fcall
      - :b
      - - :array
        - - :vcall
          - :c
        - - :vcall
          - :d

Guy passed away earlier this year. His genius was admired and he will be missed by the entire Ruby community.

One more gotcha on operator precedence.

According to the Programming Ruby chapter on expressions, the difference between the && (double ampersand) and and operators, is precedence ordering: && has higher binding than and.

>> false and true ? 'chunky' : 'bacon'
false
>> false && true ? 'chunky' : 'bacon'
"bacon"
>> (false and true) ? 'chunky' : 'bacon'
"bacon"

The or and || (double pipe) operators behave similarly.

These two code snippets also have very different abstract syntax trees. Seeing the difference will also further clarify things.

>> y pt.parse_tree_for_string("false and true ? 'chunky' : 'bacon'")
- - -
- - :and
  - - :false
  - - :if
    - - :true
    - - :str
      - chunky
    - - :str
      - bacon


>> y pt.parse_tree_for_string("false && true ? 'chunky' : 'bacon'")
- - -
- - :if
  - - :and
    - - :false
    - - :true
  - - :str
    - chunky
  - - :str
    - bacon

Uses the ruby2ruby and ParseTree gems.

Want to know more?

I'm Marc Chung, and you're reading Nothing ventured, Nothing gained, a blog about building beautiful software. I'm the founder of OpenRain Software, a web design and development company located in Arizona, where I make millions of users happy by building breathtaking software with brilliant people.

Presentations, Talks, Etc