Issue #5553 has been updated by Alexey Muranov.


I see.  But then you may also want to pass a second procedure which is run if the key does not exist, and to have both the key and the value passed to the procedures, that is to introduce a method of the form #fetch_and_use(key, proc_if_key_found, proc_if_not), but this will cost having to store the procedures in variables for a one-time use.  Also I am afraid that optimizing like this for all possible use cases may require introducing many new methods.

On the other hand, if you want to use a hash in this way with same procedures multiple times, then what about adding a method `Hash#on_found_proc=` analogous to  `Hash#default_proc=` to be able to do like this:

a = {morning: "??????????", daytime: "???????????", evening: "?????????????", nothing: nil}
a.default =  "???????"
a.on_found_proc = proc do |hash,key,value|
  "#{value}????!"
end
a[:morning]  # => "??????????????!"
a[:night]       # => "???????"

----------------------------------------
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