Created
January 22, 2016 03:37
-
-
Save chaupt/6f5e5cda94a254110433 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "minitest/autorun" | |
# ruby -Ilib:test fetch_values.rb | |
class Hash | |
def monkey_fetch_values(*keys) | |
keys.inject([]) do |a,k| | |
if self.has_key?(k) | |
a << self[k] | |
else | |
if block_given? | |
a << yield(k) | |
else | |
raise KeyError.new("key not found: \"#{k}\"") | |
end | |
end | |
a | |
end | |
end | |
end | |
describe Numeric do | |
describe "#monkey_fetch_values" do | |
before do | |
@hash = {a: 1, b: 2, c: 3, d: 4} | |
end | |
it "returns an array of values for the given keys" do | |
@hash.monkey_fetch_values(:a, :b, :c, :d).must_equal [1,2,3,4] | |
end | |
it "returns an empty array if there are no arguments" do | |
@hash.monkey_fetch_values().must_equal [] | |
end | |
it "raises error if a key is not present" do | |
proc { @hash.monkey_fetch_values(:d, :e) }.must_raise KeyError | |
end | |
it "doesn't raise an error if key is present with nil value" do | |
@hash[:e] = false | |
@hash[:f] = nil | |
@hash.monkey_fetch_values(:d, :e, :f).must_equal [4, false, nil] | |
end | |
it "doesn't mutate the hash" do | |
@hash.monkey_fetch_values(:a) | |
@hash.must_equal(a: 1, b: 2, c: 3, d: 4) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For folks at #SacRuby today, this is the implementation for one of @thomchop's problems. Sorry about the projector!