Project

General

Profile

Actions

Feature #5553

closed

A method for Hash that works differently depending on whether a key exists

Added by sawa (Tsuyoshi Sawada) over 12 years ago. Updated over 11 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-dev:44779]

Description

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.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0