Last active
January 2, 2016 09:39
-
-
Save rwz/8284868 to your computer and use it in GitHub Desktop.
An interesting Ruby problem
This file contains hidden or 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
class MyHash < Hash | |
undef_method :fetch | |
def fetch(*) | |
# your code goes here | |
end | |
end | |
require "rspec/autorun" | |
describe MyHash do | |
subject{ MyHash[:key, :value] } | |
context "#fetch" do | |
it "returns value when key is present" do | |
expect(subject.fetch(:key)).to eq(:value) | |
end | |
it "returns value when key is present regardless other arguments" do | |
expect(subject.fetch(:key, :lol){ :wut }).to eq(:value) | |
end | |
it "raises ArgumentError when too many arguments are provided" do | |
expect{ subject.fetch(:lol, :wut, :fizz) }.to raise_error(ArgumentError) | |
end | |
it "throws an error when key is not present" do | |
expect{ subject.fetch(:lol) }.to raise_error(KeyError) | |
end | |
it "returns a provided value if key is not present" do | |
expect(subject.fetch(:lol, :another_value)).to eq(:another_value) | |
end | |
it "returns nil when it's provided as a value" do | |
expect(subject.fetch(:lol, nil)).to eq(nil) | |
end | |
it "executes block when key is not present" do | |
expect(subject.fetch(:lol){ :another_value }).to eq(:another_value) | |
end | |
it "executes block if both block and default value are provided" do | |
expect(subject.fetch(:lol, :wut){ :another_value }).to eq(:another_value) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment