Skip to content

Instantly share code, notes, and snippets.

@doug7410
Created January 15, 2015 03:56
Show Gist options
  • Save doug7410/95c363638eafcd652026 to your computer and use it in GitHub Desktop.
Save doug7410/95c363638eafcd652026 to your computer and use it in GitHub Desktop.
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=NameError, &block)
if 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(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