The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Ruby: operator precedence of && and = (which also applies to || or)

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jay Fields

Posts: 765
Nickname: jayfields
Registered: Sep, 2006

Jay Fields is a software developer for ThoughtWorks
Ruby: operator precedence of && and = (which also applies to || or) Posted: Aug 5, 2007 12:47 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Jay Fields.
Original Post: Ruby: operator precedence of && and = (which also applies to || or)
Feed Title: Jay Fields Thoughts
Feed URL: http://blog.jayfields.com/rss.xml
Feed Description: Thoughts on Software Development
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jay Fields
Latest Posts From Jay Fields Thoughts

Advertisement
Recently a bug popped up on my project surrounding code similar to the following sample.

total = shopping_cart.empty? and shopping_cart.total

The problem with the above code is that it evaluates as if it were the snippet below.

(total = shopping_cart.empty?) and shopping_cart.total

It should be obvious that setting the total to true or false is not the intended behavior.

The problem with the original snippet is the usage of the 'and' operator. The Ruby operator precedence table shows that '=' has as higher precedence than the 'and' operator.

The solution is to use the '&&' operator instead of the 'and' operator. The precedence table shows that the '&&' operator has a higher precedence than the '=' operator. Therefore, the following two lines of code are basically the same.

total = shopping_cart.empty? && shopping_cart.total
total = (shopping_cart.empty? && shopping_cart.total)

As the title says, the same rules apply to the precedence of '||' and 'or'.

Read: Ruby: operator precedence of && and = (which also applies to || or)

Topic: Error: (Cylon debugger): “This application has requested the Runtime to terminate it in an... Previous Topic   Next Topic Topic: One of the Web's Little Mysteries

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use