The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
A Ruby reject! that returns the rejected items

0 replies.

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 flat view of this topic  Flat View
Previous Topic   Next Topic
Threaded View: This topic has 0 replies on 1 page
Jamie Hill

Posts: 161
Nickname: jamie007
Registered: Nov, 2006

Jamie Hill is Managing Director of SonicIQ Limited in the UK specialising in XHTML, CSS and Rails.
A Ruby reject! that returns the rejected items Posted: Jul 25, 2007 4:25 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Jamie Hill.
Original Post: A Ruby reject! that returns the rejected items
Feed Title: The Lucid
Feed URL: http://feeds.feedburner.com/thelucid
Feed Description: Lightweight ramblings and tips on Ruby and Rails.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jamie Hill
Latest Posts From The Lucid

I often need to do a reject! and return the rejected items instead of the modified collection. This saves having to do a select beforehand.

An example of how accomplish this:

options = { :a => 1, :b => 2, :c => 3 }
rejects = Hash[*options.select { |k, v| k == :b && options.delete(k) }.flatten]

assert_equal { :a => 1, :c => 3 }, options
assert_equal { :b => 2 }, rejects

This could be written as a method of the Hash class and an alternative for Array.

For Hash, the code would look something like:

class Hash
  def extract!
    Hash[*self.select { |k, v| yield(k, v) && self.delete(k) }.flatten]
  end
end

options = { :a => 1, :b => 2, :c => 3 }
rejects = options.extract! { |k, v| k == :b }

assert_equal { :a => 1, :c => 3 }, options
assert_equal { :b => 2 }, rejects

If I am missing something obvious in Ruby that accomplishes the same, please leave a comment.

Read: A Ruby reject! that returns the rejected items


Topic: hoe version 1.2.2 has been released! Previous Topic   Next Topic Topic: Applescript is a PITA: Exporting Keynote as PDF

Sponsored Links



Google
  Web Artima.com   

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