Comparison operator on string attributes of ActiveRecord objects

June 5, 2009 § Leave a comment

Here’s a little gotcha for you which caught me out by surprise, obvious when you think about it, but irritating if you miss it: the ruby String comparison operator does case-sensitive comparisons.

# Good:
['C', 'b', 'A', 'D'].sort #=> ['A', 'b', 'C', 'D']
 
# Bad (what <=> gives you out the box):
['C', 'b', 'A', 'D'].sort #=> ['A', 'C', 'D', 'b']

For a nice efficient implementation of a AR model comparitor use the String#casecmp method for a case-insensitive comparison:

class MyObject
  def <=>(other)
    self.my_attribute.casecmp(other.my_attribute)
  end
end

Original post: Comparison operator on string attributes of ActiveRecord objects.

Advertisements

Tagged: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Comparison operator on string attributes of ActiveRecord objects at Fringley's Blog.

meta

%d bloggers like this: