Syntax
hash.transform_values { |value| new_value }Examples
Transforming Hash Values
Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
raw = { small: "2", large: "5" }
quantities = raw.transform_values { |value| Integer(value) }
puts quantities[:small] + quantities[:large]
puts raw[:small].class- Expected output: 7 String
- Only the new hash contains converted integers. The non-bang method leaves the original strings intact.
Best practices
- Use Integer for strict numeric conversion when malformed data should raise.
- Choose transform_values! only when callers expect in-place mutation.
Runtime & versions
Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Ruby documentation