Instructions
Create a function get_city that extracts the city from a nested
user hash structure. Return nil if any key is missing.
Use dig for safe nested access:
ruby
hash = { user: { address: { city: "NYC" } } }
hash.dig(:user, :address, :city) # => "NYC"
hash.dig(:user, :phone, :number) # => nil (no error!)
Expected structure:
ruby
{ user: { address: { city: "..." } } }
Hints:
- Use .dig(:user, :address, :city)
- dig returns nil if any key is missing
- No need for nil checks or rescue
Your Code
def get_city(data) data.dig(:user, :address, :city) end
RSpec.describe "get_city" do
it "extracts city from nested hash" do
data = { user: { address: { city: "Tokyo" } } }
expect(get_city(data)).to eq("Tokyo")
end
it "returns nil for missing address" do
data = { user: { name: "Alice" } }
expect(get_city(data)).to be_nil
end
it "returns nil for missing user" do
data = { other: "data" }
expect(get_city(data)).to be_nil
end
it "returns nil for empty hash" do
expect(get_city({})).to be_nil
end
end
Results
Click "Run Tests" to see results