Last active
August 29, 2015 14:13
-
-
Save doug7410/ac05acee72dda1777669 to your computer and use it in GitHub Desktop.
code challenge from Miacah Woods - 1.5 hours
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, set_value='') | |
if self.has_key?(key) | |
self[key] | |
else | |
if set_value == '' && !block_given? | |
raise KeyError, 'The key was not in the array' | |
else | |
if block_given? | |
yield | |
else | |
set_value | |
end | |
end | |
end | |
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