Hash#sliceが欲しい をさらに拡張。

指定したキーを取り除いたHashを返すHash#exceptを追加。 併せて、既存のHash#sliceHash#onlyに改名してみました。

hash_ext.rb

   1  class Hash
   2    def only(*args)
   3      args = *args if args[0].is_a? Array
   4      args.inject({}){|hash, key| hash[key] = self[key]; hash}
   5    end
   6    
   7    def except(*args)
   8      args = *args if args[0].is_a? Array
   9      args.inject(dup){|hash, key| hash.delete(key); hash}
  10    end
  11  end

使い方:

   1  cond = params.only :year, :month, :day
   2  ma = MonthlyArchive.find :all, :conditions => cond.except(:day)

posted by Png genki on Thu 29 Nov 2007 at 03:08

Comments:

or Preview
Social Bookmarks
  • Delicious
  • B_entry228
  • Clip_16_12_w
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ