Using transform_values to Transform Hash Values in Ruby

In Ruby 2.4, a new method called transform_values was introduced to help transform hash values using a block. This method can be particularly useful when you need to modify the values in a hash without changing the keys.

To use transform_values, call it on the hash that you want to transform, and pass in a block that takes each value as an argument. Here’s an example of how to use transform_values to transform hash values:

1
2
3
data = { a: 1, b: 2, c: 3 }
transformed_data = data.transform_values { |value| value * 2 }
# { a: 2, b: 4, c: 6 }

In this example, the data hash contains three key-value pairs. The transform_values method is called on the data hash, and a block is passed in that multiplies each value by 2. The result is a new hash called transformed_data that contains the same keys as data, but with the values transformed.

The transform_values method is a handy shortcut for transforming hash values using a block, and can help make your code more concise and readable. You can use it to transform the values of any hash, including ones that you generate dynamically.

Here’s a final example of how to use transform_values to generate a hash of file sizes in kilobytes:

1
2
file_sizes = Dir.glob('*.txt').each_with_object({}) { |filename, hash| hash[filename] = File.size(filename) }
file_sizes_in_kb = file_sizes.transform_values { |size| size / 1024.0 }

In this example, the file_sizes hash is generated using Dir.glob and File.size, and contains the sizes of all text files in the current directory. The transform_values method is called on file_sizes, and a block is passed in that divides each value by 1024 to convert the size to kilobytes. The result is a new hash called file_sizes_in_kb that contains the same keys as file_sizes, but with the values transformed to kilobytes.

By using transform_values, you can easily transform hash values using a block and avoid having to manually iterate over the hash.