Search code examples
rubyhashsafe-navigation-operator

Safe navigation operator for hash with string keys


I have a problem:

data = { 'str_key' => ['string1', 'string2'] }

# @param [Hash] data - hash with String key
# @return [boolean]
def some_logic_test?(data)
  data&.<what_to_do_with_string_key?>.include?('string1')
end

How can I use the safe navigation operator &. for hash with string keys? Keys conversion will by [sic] obligatory?


Solution

  • The fact that this key is String isn't really relevant here. What you want (well, I guess) is to use safety operator with [] method and you can do it like this:

    data&.[]('str_key')&.include?('string1')
    

    You can also make use of Hash#dig method, I think it will improve readability of this code:

    data&.dig('str_key')&.include?('string1')
    

    Hash#dig also has the advantage of working properly with nested hashes (it was in fact designed to handle this case):

    data = { 'str_key' => { 'str_key1' => { 'str_key2' => 'str_value' } } }
    data.dig('str_key', 'str_key1', 'str_key2')
    # => 'str_value'