Rigby K.
Rigby K.

Reputation: 31

How to use "for" and change values in a ruby hash?

if have the hash:

hash = {a:1, b: 2, c: 3}

tried this:

for value in hash.values do
    value = value * value
end

but return the same value no the value desired, I find a solution:

hash.transform_values{ |value| value * value}
=> {:a=>1, :b=>4, :c=>9}

but want to do with a for loop, how to do?

Upvotes: 0

Views: 95

Answers (3)

Slava Zharkov
Slava Zharkov

Reputation: 237

We have a rich standard lib to work with collections in Ruby. It is very useful and covers most needed cases. We have a great methods Enumerable#map, Enumerable#filter, Enumerable#reduce in ruby and many others. Please, read the documentation.

The general purpose way is to generate a new hash:

new_hash = hash.each_with_object({}) { |(k, v), acc| acc[k] = v * v }

For Ruby since 2.4.0 you can use the Hash#transform_values method:

hash.transform_values{ |value| value * value }

We prefer to use map, filter, transform_values instead of for because of several reasons. Such as:

  • minimize data mutation and side effects;
  • ability to chain methods like collection.filter(&:empty?).map(&:size)

Upvotes: 3

Davinj
Davinj

Reputation: 347

hash.each{ |k, v| hash[k] = v * v }

Upvotes: 0

Ursus
Ursus

Reputation: 30071

I think this is the closest to what you want

for k, v in hash do
  hash[k] = v * v
end

Upvotes: 0

Related Questions