29th Thu
Hash#except and Hash#only
Hash#sliceが欲しい
をさらに拡張。
指定したキーを取り除いたHashを返すHash#exceptを追加。
併せて、既存のHash#sliceはHash#onlyに改名してみました。
hash_ext.rb
ruby>>
class Hash
def only(*args)
args = *args if args[0].is_a? Array
args.inject({}){|hash, key| hash[key] = self[key]; hash}
end
def except(*args)
args = *args if args[0].is_a? Array
args.inject(dup){|hash, key| hash.delete(key); hash}
end
end
<<--
使い方:
ruby>>
cond = params.only :year, :month, :day
ma = MonthlyArchive.find :all, :conditions => cond.except(:day)
<<--
posted by
genki on Thu 29 Nov 2007 at 03:08 with 0 comments