mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
add Hash#fetch; close #2134
This commit is contained in:
@@ -13,4 +13,18 @@ class Hash
|
||||
|
||||
alias each_pair each
|
||||
alias update merge!
|
||||
|
||||
def fetch(key, none=NONE, &block)
|
||||
unless self.key?(key)
|
||||
if block
|
||||
block.call
|
||||
elsif none != NONE
|
||||
none
|
||||
else
|
||||
raise RuntimeError, "Key not found: #{key}"
|
||||
end
|
||||
else
|
||||
self[key]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -27,3 +27,15 @@ assert('Hash#values_at') do
|
||||
h = Hash.new { |hash,k| hash[k] = k }
|
||||
assert_equal keys, h.values_at(*keys)
|
||||
end
|
||||
|
||||
assert('Hash#fetch') do
|
||||
h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
|
||||
assert_equal "feline", h.fetch("cat")
|
||||
assert_equal "mickey", h.fetch("mouse", "mickey")
|
||||
assert_equal "minny", h.fetch("mouse"){"minny"}
|
||||
begin
|
||||
h.fetch("gnu")
|
||||
rescue => e
|
||||
assert_kind_of(StandardError, e);
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user