Instructions
Create a function normalize_user that takes a user hash and:
1. Converts all keys to symbols (using transform_keys)
2. Strips whitespace from all string values (using transform_values)
Hash transformation methods:
ruby
hash.transform_keys { |k| k.to_sym }
hash.transform_values { |v| v.strip }
Example:
```ruby
normalize_user({ "name" => " Alice ", "email" => " a@b.com " })
=> { name: "Alice", email: "a@b.com" }
Hints:
- Chain transform_keys and transform_values
- Use .to_sym to convert string keys to symbols
- Use .strip for strings, handle non-strings
Your Code
def normalize_user(user)
user
.transform_keys(&:to_sym)
.transform_values { |v| v.is_a?(String) ? v.strip : v }
end
RSpec.describe "normalize_user" do
it "converts keys to symbols and strips values" do
input = { "name" => " Alice ", "email" => " a@b.com " }
result = normalize_user(input)
expect(result).to eq({ name: "Alice", email: "a@b.com" })
end
it "handles non-string values" do
input = { "name" => " Bob ", "age" => 25 }
result = normalize_user(input)
expect(result).to eq({ name: "Bob", age: 25 })
end
it "handles empty hash" do
expect(normalize_user({})).to eq({})
end
end
Results
Click "Run Tests" to see results