Ruby on Rails: Hash#Except and Converting Arrays to Args

Posted by Jeremy Gillick on 21 Jul 2008 10:32 pm in Code

Tonight I was working on rewriting the event creation flow for MixerMixer, the social event community I’ve been building, and couldn’t figure out why the Hash#except method wasn’t working.

My goal was to exclude users who were already invited to the event so they wouldn’t be reinvited when the user edits it. So I have 2 hashes: one with the users that are selected and the other with the users who have already been invited to the event. Should be simple:

# Hash format: user_id => user_id
# current_invites = { 567 => 567, 890 => 890}
# selected_invites = { 123 => 123, 567 => 567, 890 => 890}

add = selected_invites.except(@current_invites.keys)

# Should return { 123 => 123 }
# It actually returns { 123 => 123, 567 => 567, 890 => 890}

As you can see, it returns the full hash and doesn’t remove anything. This will not do.

It tuns out that I missunderstood the Rails documentation. Hash#except doesn’t take in an array of keys to remove it takes in a list of arguments. Here’s a simple example:

add = selected_invites.except(567, 890)
# Returns { 123 => 123 }

Now I needed to figure out how to convert the @current_invites.keys array into an argument list. It turns out to be as easy as adding an asterisk in front of it:

add = selected_invites.except(*@current_invites.keys)
# Returns { 123 => 123 }

Success!

Enjoy.

One Response

  1. Bookmarks about Hash Says:

    September 22nd, 2008 at 11:53 pm

    […] - bookmarked by 1 members originally found by stijngruwier on 2008-09-14 Ruby on Rails: Hash#Except and Converting Arrays to Args http://blog.mozmonkey.com/2008/ruby-on-rails-hashexcept-and-converting-arrays-to-args/ - […]

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.