Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Hash values?

Tags:

syntax

ruby

hash

People also ask

Can hash values change?

The contents of a file are processed through a cryptographic algorithm, and a unique numerical value – the hash value - is produced that identifies the contents of the file. If the contents are modified in any way, the value of the hash will also change significantly.

How do you update a value in a hash Ruby?

Modifying hashes in Ruby: Hash can be modified by adding or deleting a key value/pair in an already existing hash. Also, you can change the existing value of key in the hash.

Why would a hash change?

One flipped bit in a file will cause an entirely new hash in a secure hashing algorithm. In short - if you see a different hash, the file's contents have changed, even if it is by one bit.


my_hash.each { |k, v| my_hash[k] = v.upcase } 

or, if you'd prefer to do it non-destructively, and return a new hash instead of modifying my_hash:

a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k] = v.upcase; h } 

This last version has the added benefit that you could transform the keys too.


Since ruby 2.4.0 you can use native Hash#transform_values method:

hash = {"a" => "b", "c" => "d"}
new_hash = hash.transform_values(&:upcase)
# => {"a" => "B", "c" => "D"}

There is also destructive Hash#transform_values! version.


You can collect the values, and convert it from Array to Hash again.

Like this:

config = Hash[ config.collect {|k,v| [k, v.upcase] } ]

This will do it:

my_hash.each_with_object({}) { |(key, value), hash| hash[key] = value.upcase }

As opposed to inject the advantage is that you are in no need to return the hash again inside the block.


There's a method for that in ActiveSupport v4.2.0. It's called transform_values and basically just executes a block for each key-value-pair.

Since they're doing it with a each I think there's no better way than to loop through.

hash = {sample: 'gach'}

result = {}
hash.each do |key, value|
  result[key] = do_stuff(value)
end

Update:

Since Ruby 2.4.0 you can natively use #transform_values and #transform_values!.