The Artima Developer Community
Sponsored Link

PHP Buzz Forum
Query Methods in Rails and true/false

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
Joe Grossberg

Posts: 244
Nickname: jgrossberg
Registered: Mar, 2003

Joe Grossberg loves Python, PHP and Programming
Query Methods in Rails and true/false Posted: Sep 21, 2007 9:12 AM
Reply to this message Reply

This post originated from an RSS feed registered with PHP Buzz by Joe Grossberg.
Original Post: Query Methods in Rails and true/false
Feed Title: Joe Grossberg
Feed URL: http://feeds.feedburner.com/joegrossbergatom/
Feed Description: My bullshit, your brain.
Latest PHP Buzz Posts
Latest PHP Buzz Posts by Joe Grossberg
Latest Posts From Joe Grossberg

Advertisement

In Ruby, unlike many other languages, only false and nil evaluate to false.

However, I learned today that the ActiveRecord::Base class in Rails gives us not only attribute setters and getters, but a query method too.

And this query method has its own rules.

Where o is an instance of an ActiveRecord class, and name is a column/attribute:

>> o.name = nil
=> nil
>> o.name?
=> false
>> o.name = false => false >> o.name? => false
>> o.name = '' => "" >> o.name? => false
>> o.name = 0 => 0 >> o.name? => false
>> o.name = [] => [] >> o.name? => true
>> o.name = {} => {} >> o.name? => true
>> o.name = 0.0 => 0.0 >> o.name? => true

So this has its own set of rules: false and nil still evaluate to false, but so do 0 and an empty string. However, empty arrays, empty hashes and the 0.0 float evaluate to true.

For [] and {}, you can do foo.empty?. But for 0.0, you have to do foo.zero?.

Ugh; more arbitrary stuff to memorize (or test in the console).

I wish there was some method that combined ?, empty? and zero?. Perhaps there is one that I've overlooked?

Read: Query Methods in Rails and true/false

Topic: Shizzle Gridizle Previous Topic   Next Topic Topic: Google Docs - Now with online presentations! Yarr!

Sponsored Links



Google
  Web Artima.com   

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