Skip to content

Instantly share code, notes, and snippets.

@doug7410
Created January 14, 2015 02:59
Show Gist options
  • Save doug7410/de8ce54369a4e9d7b5bd to your computer and use it in GitHub Desktop.
Save doug7410/de8ce54369a4e9d7b5bd to your computer and use it in GitHub Desktop.
code challenge from Miacah Woods - extra credit :)
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='', &block)
if self.has_key?(key)
self[key]
else
return_given_value_or_raise_exception(set_value, &block)
end
end
private
def return_given_value_or_raise_exception(set_value, &block)
raise KeyError, 'key not in the array' if set_value == '' && !block_given?
(block_given?)? yield : set_value
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