Skip to content

Hash goodness! (or nice methods for working with hashes in Ruby & Rails)

I wish these methods were in ruby proper (or even just Rails).

I’ve been using at Zaadz. them to clear certain parameters out of parameter hashes in Rails, and I got tired of typing `something.delete_if { |k,v| %w{this that}.include?(k) }`… so I wrote a couple of extensions to Hash that let you filter a hash, selecting all __except__ the keys you specify or selecting __only__ the keys you specify.

And just because, I dedicate this one to my friend [Steph][1]:

[1]:http://stephalicio.us/

class Array
# Converts a nested array suchs a [[1,2],[3,4]] into {1 => 2, 3 => 4}
def to_h
hash = {}
self.each do |ary|
hash[ary.first] = ary.last
end
return hash
end
end

class Hash
# Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3}
def except(*keys)
self.reject { |k,v|
keys.include? k.to_sym
}
end

# Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1}
def only(*keys)
self.select { |k,v|
keys.include? k.to_sym
}.to_h
end
end

2 Comments

  1. Have you considered making these modifications a plugin that extends the ActiveSupport::CoreExtension module? I’ve taken this approach for additions that I’ve wanted to make to the standard library and it works out pretty well.

    Posted on 13-Apr-06 at 8:16 pm | Permalink
  2. stephanie wrote:

    Thanks honey :)

    Posted on 23-Apr-06 at 11:58 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*