以前紹介した Hash#only にちょっとした修正。

lib/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] if include? key; hash}
   5    end
   6  
   7    def only!(*args)
   8      args = *args if args[0].is_a? Array
   9      args.inject({}){|hash, key| hash[key] = self[key]; hash}
  10    end

以前のHash#onlyは、指定したキーが存在しない場合でも

   1  {:foo => 1}.only(:bar) #=> {:bar => nil}

というように、nilを指すHashを返していましたが、 キーが存在しない場合に空のHashを返すようにしてみました。 従来の挙動をするメソッドは、Hash#only!と感嘆符付きの メソッドにしています。 修正後の挙動は以下の通り。

   1  {:foo => 1}.only(:bar) #=> {}
   2  {:foo => 1}.only!(:bar) #=> {:bar => nil}

posted by Png genki on Sat 19 Jan 2008 at 13:30
Contents
Hash#only and Hash#only!
Comments
瀧内元気: MacOS版は以下にあります * [genki/ViMouse](https://githu... '23-1
dsjf: https://gist.github.com/6bf1bf2c3cbb5eb6e7a7 これ... '13-1
瀧内元気: おお、チェックしてみます。thx! '11-12
overisland: Reeder for iPhone もこの UI を実装していますね。 '11-12
瀧内元気: その情報は見たのですが、以下のサイトによると、現在はまた必要になってるっぽいんですよね。 ... '11-12
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ