How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?

Ruby 2.3.0 introduced a method called dig on both Hash and Array. name = params.dig(:company, :owner, :name) It returns nil if the key is missing at any level. If you are using a version of Ruby older than 2.3, you can install a gem such as ruby_dig or hash_dig_and_collect, or implement the functionality yourself: module … Read more

Hashes of Hashes Idiom in Ruby?

You can pass the Hash.new function a block that is executed to yield a default value in case the queried value doesn’t exist yet: h = Hash.new { |h, k| h[k] = Hash.new } Of course, this can be done recursively. There’s an article explaining the details. For the sake of completeness, here’s the solution from … Read more

Converting nested hash keys from CamelCase to snake_case in Ruby

If you use Rails: Example with hash: camelCase to snake_case: hash = { camelCase: ‘value1’, changeMe: ‘value2’ } hash.transform_keys { |key| key.to_s.underscore } # => { “camel_case” => “value1”, “change_me” => “value2” } source: http://apidock.com/rails/v4.0.2/Hash/transform_keys For nested attributes use deep_transform_keys instead of transform_keys, example: hash = { camelCase: ‘value1’, changeMe: { hereToo: { andMe: ‘thanks’ … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)