From: Yukihiro Matsumoto Date: 2011-11-03T19:49:10+09:00 Subject: [ruby-dev:44792] [ruby-trunk - Feature #5553][Feedback] A method for Hash that works differently depending on whether a key exists Issue #5553 has been updated by Yukihiro Matsumoto. Status changed from Open to Feedback 「fetchや[]を頻繁に呼びたくない」という意図は伝わらないでも無いですが、でもそれよりもif_keyメソッドのほうが嬉しい局面というのがあまり想像できません。単にメソッドでラップすればいいんじゃないですか? 正直、この例では全然嬉しくないと思います。もうちょっと人工的でない例だと嬉しさがイメージできるかもしれません。 ---------------------------------------- Feature #5553: A method for Hash that works differently depending on whether a key exists http://redmine.ruby-lang.org/issues/5553 Author: Tsuyoshi Sawada Status: Feedback Priority: Normal Assignee: Category: Target version: A method Hash#if_key(key, [default], &pr) which works like the following will be often used, and is useful. a = {morning: "おはよう", daytime: "こんにちは", evening: "こんばんは", nothing: nil} a.if_key(:morning){|str| "#{str}世界!"} #=> "おはよう世界!" a.if_key(:nothing){|str| "#{str}世界!"} #=> "世界!" a.if_key(:midnight){|str| "#{str}世界!"} #=> nil a.if_key(:nothing, "どうも"){|str| "#{str}世界!"} #=> "どうも" That is, when `key' exists, then the corresponding value will be passed to `pr'. Otherwise, the given `default' or the implicit default will be returned. -- http://redmine.ruby-lang.org