3

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 4
    Why do you want to use the safe navigation operator in the first place? Could `data` be `nil`? Could `data` not be a hash? Could `'str_key'` be missing? Could `'str_key'` be present and not be an array? What's the actual problem you're trying to solve here? – Stefan Feb 13 '19 at 10:23
  • Your problem is not at all clear. – sawa Feb 13 '19 at 10:27
  • 1
    Safe navigation seems a bit obtuse here given that a simple `return unless data` guard clause would be perfectly appropriate (and far more readable) in this method. – engineersmnky Feb 13 '19 at 14:29

1 Answers1

10

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'
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • So, maybe better in this way: ```data['str_key']&.include?('string1') ``` Which solution will be the best? – Radosław Sakowicz Feb 13 '19 at 10:19
  • 1
    @RadosławSakowicz it depends on the input data, like Stefan mentioned in the comment below your question. If it's possible for `data` to be `nil`, you have to take this possibility into account. Otherwise `data['str_key']&.include?('string1')` is enough, obviously. – Marek Lipka Feb 13 '19 at 10:26