top of page

🚀 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 tudo

Me de o contexto e vou lhe dar um resultado

No vídeo abaixo eu compartilho que muitas vezes problemas, tarefas, fixes são colocados em pauta para desenvolvedores, mas algumas coisas não são levadas em consideração como: Qual o contexto que foi

Captura de tela de 2024-01-01 22-06-25.png

Hi, I'm Rodrigo Toledo

A full-stack developer skilled in both front-end and back-end development, building and maintaining web applications

  • Facebook
  • Youtube
  • LinkedIn
  • Instagram

I don't know everything, help me

Every day, I try to improve what I know about frameworks, and when this occurs, I'll try to share it with the community. Every day, I try to improve my knowledge about frameworks. When this happens, I will try to share it with the community.

Subscribe

Thanks for submitting!

bottom of page