From: Tsuyoshi Sawada Date: 2011-11-03T17:43:36+09:00 Subject: [ruby-dev:44786] [ruby-trunk - Feature #5553] A method for Hash that works differently depending on whether a key exists Issue #5553 has been updated by Tsuyoshi Sawada. The whole point of this suggestion is that I feel some redundancy to have to call the method `fetch` or `[]` on the hash after checking that the key exists using `key?`. With this proposed method, the method call `fetch` or `[]` is unnecessary, and you can just refer to a block variable. ---------------------------------------- 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: Open 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