Created
January 15, 2015 03:58
-
-
Save doug7410/d68d60d3e4c9ab636de3 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 "rspec/autorun" | |
class MyHash < Hash | |
undef_method :fetch | |
# Implement the method fetch without using `super` | |
# HINT: replace star with the argument(s) you want | |
def fetch(key, value=NameError, &block) | |
(has_key?(key))? self[key] : return_value_or_raise_exception(value, &block) | |
end | |
private | |
def return_value_or_raise_exception(value, &block) | |
raise KeyError, 'key not in the array' if arguments_missing?(value, &block) | |
(block_given?)? yield : value | |
end | |
def arguments_missing?(value, &block) | |
value == NameError && !block_given? | |
end | |
end | |
RSpec.describe MyHash do | |
subject{ MyHash[:foo, "foo", :bar, "bar"] } | |
it "gets the value by key" do | |
expect(subject.fetch(:foo)).to eq("foo") | |
end | |
it "raises KeyError when trying to access non-existing key" do | |
expect{ subject.fetch(:baz) }.to raise_error(KeyError) | |
end | |
it "returns the second argument when trying to access non-existing key" do | |
expect(subject.fetch(:baz, "set value")).to eq("set value") | |
expect(subject.fetch(:baz, nil)).to be_nil | |
expect(subject.fetch(:baz, false)).to eq false | |
end | |
it "executes block if given when trying to access non-existent key" do | |
expect(subject.fetch(:baz){ "set value" }).to eq("set value") | |
expect(subject.fetch(:baz, "no good"){ "set value" }).to eq("set value") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment