Had this as part of an interview,I guessed it took incoming data, translated it into local language then commits to database? Which was obviously wrong.
def optimize(hsh)
hsh.reduce({}) do |new_hsh, (k,v)|
new_hsh[k.to_sym] = v.kind_of?(Hash) ? optimize(v) : v
new_hsh
end
end
It looks like it just recursively converts keys from nested hashes to symbols.
optimize({'k' => {'l' => 'v'}})
#=> {:k=>{:l=>"v"}}
Optimize is a poor name and each_with_object
should be used instead of reduce
:
def symbolize_keys(hash)
hash.each_with_object({}) do |(k, v), new_hash|
new_hash[k.to_sym] = v.is_a?(Hash) ? symbolize_keys(v) : v
end
end
puts symbolize_keys('k' => { 'l' => 'v' })
#=> {:k=>{:l=>"v"}}
This method could be used to make sure that a nested hash has the correct keys. Some devs like to use string keys, others prefer symbols :
{'a' => 'b'}[:a]
#=> nil
symbolize_keys({'a' => 'b'})[:a]
#=> 'b'
Servers talk to each others with strings but Rails code is often written with symbols as keys. That's one of the reasons why HashWithIndifferentAccess
exists.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.