🚀 Ruby Tip: Leveraging `transform_values` to Modify Hash Values
In Ruby, the `transform_values` method provides a concise way to modify the values of a hash. It accepts a block as an argument and returns a new hash with the values transformed according to the provided block.
# Original Hash
scores = { alice: 80, bob: 65, charlie: 90 }
# Adding 10 points to each score
adjusted_scores = scores.transform_values { |score| score + 10 }
puts adjusted_scores
# Output: { alice: 90, bob: 75, charlie: 100 }
In this example:
We start with an original hash called `scores`, containing keys representing people's names and values representing their scores.
We use `transform_values` to add 10 points to each score. The block { |score| score + 10 } is applied to each value in the hash, adding 10.
The result is a new hash called `adjusted_scores` with the modified values.
Using `transform_values` offers a clean and efficient way to apply a transformation to all values in a hash without manual iteration. It's a powerful tool in Ruby's arsenal for working with hashes efficiently!
Posts recentes
Ver tudoComo já dizia na canção: um pouco de malandragem… pois não conheço a verdade. Já parou pra pensar no momento atual de sua vida que...
You know, I often say: I don’t claim to hold all the answers, but give me a problem, and I’ll strive to solve it. The issue as I see it...
Comments