July 10, 2007

Posted by John

Older: Edge Rails Bites Back

Newer: Clogging: Code Blogging

Hash#except

My apologies for being sparse around here lately. I’m going to try to post a few smaller items in order to get me motivated to post on all the stuff I’ve been learning of late. For starters, I just saw that Hash got a new method in edge rails. Hash#except was just added to hash. It is a simple method which is the inverse of Hash#slice — return the hash except the keys that are specified.

I’ve used something similar to this in the past so it’s nice to see it in edge. I found it handy for models that didn’t inherit from active record and as such didn’t have access to attr_protected and attr_accessible.

An example use is:

original = { :a => 'x', :b => 'y', :c => 10 } 
expected = { :a => 'x', :b => 'y' }
assert_equal expected, original.except(:c)

# there is also the bang version
assert_equal expected, original.except!(:c)

0 Comments

Sorry, comments are closed for this article to ease the burden of pruning spam.

About

Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.

Projects

Flipper
Release your software more often with fewer problems.
Flip your features.