Issue #5553 has been updated by Alexey Muranov.


In your example, the :nothing key exists, so shouldn't it be
a.if_key(:nothing, "???????"){|str| "#{str}????!"} #=> "????!" ?

Why would the code with this method be better than the following one:

if a.has_key?(key)
  # block here
else
  # default value or another block here
end

or ( a.has_key?(key) ? simple operation : default )

This seems easier to read.

If you plan to always use it with the same block, maybe it should be made into a separate class with an appropriate method?
----------------------------------------
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