Skip to content

Instantly share code, notes, and snippets.

@quanon
Created April 4, 2014 08:00
Show Gist options
  • Save quanon/9970140 to your computer and use it in GitHub Desktop.
Save quanon/9970140 to your computer and use it in GitHub Desktop.
過去の遺物
##
# オープンクラスにインクルードさせるためのモジュール集
#
module Extensions
module Hash
##
# Hash の入れ子から値を取り出すためのインスタンスメソッド。
#
# (例)
# hash = {a: {b: {c: {d: "treasures"}}}}
#
# hash.salvage(:a, :b, :c) #=> {:d=>"treasures"}
# hash.salvage(:a, :b, :c, :d) #=> "treasures"
# hash.salvage(:a, :b, :c, :d, :e) #=> nil
# hash.salvage(:a, :x, :c, :d) #=> nil
# hash.salvage([:a, :b, :c, :d]) #=> "treasures"
#
def salvage(*keys)
keys.flatten!
key = keys.shift
value = self[key]
if value.kind_of?(Hash) && keys.size > 0
value.send(__method__, keys)
elsif keys.size > 0
nil
else
value
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment