Reputation: 31
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
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:
collection.filter(&:empty?).map(&:size)
Upvotes: 3
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