Home > Software design >  when each is called on a hash, is there a way to reference the hash inside the block in a shorthand
when each is called on a hash, is there a way to reference the hash inside the block in a shorthand

Time:12-24

For example

I have a hash:

@something = {a: 1, b: 2, c: 3}

I could modify the hash as follows:

@something.each { |(k,v)| @something[k] = v*2 }

is there a shorthand way of referring to the variable @something within the braces?

This could also be solved by using reduce method which avoids the issue altogether but adds weight or converting to an array and using map.

Or is it just a bad idea.

CodePudding user response:

I would use transform_values instead of each:

@something = @something.transform_values{ |v| v * 2}

Now you don't need to reference @something at all since you are just creating a new hash.

CodePudding user response:

One might also use #each_with_object to build a new hash.

@something.each_with_object({}) { |(k, v), h| h[k] = v * 2 }
# => {:a=>2, :b=>4, :c=>6}

CodePudding user response:

Although a better answer was already given, here are a couple other options:

Use merge! and just merge the original hash with itself;

@something = {a: 1, b: 2, c: 3}
@something.merge!(@something) {|k, v| v*2}
@something
#=>  {:a=>2, :b=>4, :c=>6}

Use map;

@something = {a: 1, b: 2, c: 3}
@something = @something.map{|k, v| [k, v*2]}.to_h
@something
#=>  {:a=>2, :b=>4, :c=>6}
  •  Tags:  
  • ruby
  • Related