Codectionary / Developer documentation / Ruby

Transforming Hash Values

transform_values produces a hash with the same keys and new values from a block. It is useful for normalizing all fields with a shared conversion. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

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
  1. Expected output: 7 String
  2. 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

Specifications & further reading