Why is the "transform_keys" method undefined?

This example is taken directly from the Ruby 2.4.1 documentation , and I can confirm that 2.4.1 works for me:

({a: 1, b: 2, c: 3}).transform_keys {|k| k.to_s} 

When I executed it, I get the following error:

 NoMethodError: undefined method `transform_keys' for {:a=>1, :b=>2, :c=>3}:Hash 

Why is the transform_keys method not defined?

+5
source share
2 answers

As noted in another question , it seems that http://ruby-doc.org is currently (erroneously) generating documentation for Ruby 2.4.1 based on Ruby trunk instead of the actually released version 2.4.1.

Unfortunately, the Hash#transform_keys method has not yet been released as part of any version 2.4. It was developed and included in the Ruby trunk with Feature # 13583 , but was not (yet) included in the 2.4 stable branch.

As a workaround, you can use this method:

 def transform_keys(hash) result = {} hash.each_pair do |key, value| result[yield(key)] = value end result end 

Equivalent (i.e.: a little shorter, but also a bit slower), you cpuld use this:

 def transform_keys(hash) hash.keys.each_with_object({}) do |key, result| result[(yield(key)] = hash[value] end end 

If you are in bold, you can declare this as the main patch to the Hash class, where you just need to replace every mention of Hash with self .

Please note that ActiveSupport (i.e. Rails) brings the main patch using this exact method since forever. They use a mixture of both implementations.

+5
source

Thanks Holger, you inspired me.

This works to convert keys from string to character also for nested hashes , as I need:

 class Hash def keys_to_sym result = {} self.each_pair do |key, value| value = value.keys_to_sym if value.class == Hash result[key.to_sym] = value end result end end 

So you can convert this:

 h = { "key1"=>"value1", "key2"=>"value2", "key3"=>{"key4"=>"value4", "key5"=>"value5"}, "key6"=>{"key7"=>"value7", "key8"=>{"key9"=>"value9"}} } 

in it:

 h_transformed = { :key1=>"value1", :key2=>"value2", :key3=>{:key4=>"value4", :key5=>"value5"}, :key6=>{:key7=>"value7", :key8=>{:key9=>"value9"}} } 
0
source

Source: https://habr.com/ru/post/1272108/


All Articles