Last active
August 29, 2015 14:13
-
-
Save doug7410/746026e9011d1c14c959 to your computer and use it in GitHub Desktop.
code challenge from Miacah Woods - 30 minutes
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=nil) | |
if key && self[key] | |
self[key] | |
elsif set_value | |
set_value | |
else | |
raise KeyError, 'The key was not in the array' unless self[key] | |
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 | |
skip | |
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