Instructions
Create a function get_value that takes a hash, a key, and a default value.
Return the value for the key if it exists, otherwise return the default.
Use Ruby's fetch method with a default value.
Hints:
- Use hash.fetch(key, default)
- fetch returns default if key doesn't exist
- This is safer than hash[key] || default
Your Code
def get_value(hash, key, default) hash.fetch(key, default) end
RSpec.describe "get_value" do
it "returns value when key exists" do
expect(get_value({ a: 1, b: 2 }, :a, 0)).to eq(1)
end
it "returns default when key missing" do
expect(get_value({ a: 1 }, :b, 99)).to eq(99)
end
it "works with string keys" do
expect(get_value({ "x" => 10 }, "x", 0)).to eq(10)
end
end
Results
Click "Run Tests" to see results