Search code examples
rubyhashprettier

VS Code Prettier breaking hash access


I'm trying to access data in a hash like this:

result&.data['address']['ISO3166-2-lvl4']

but when I save the file, Prettier changes it to this:

result&.data&.[]('ISO3166-2-lvl4')

which doesn't work. What is Prettier trying to do here, and how can I stop it?


Solution

  • This doesn't really work if result is nil:

    >> result = nil
    => nil
    >> result&.data[:address][:iso]
    undefined method `[]' for nil:NilClass (NoMethodError)
    

    In general you have to use &. for every method that you chain after the first &..

    Prettier is trying to call Hash#[] method with &. operator, which should look like this:

    >> result&.data&.[](:address)&.[](:iso)
    => nil
    
    # it works when you have result and data hash
    class Result
      def data = {address: {iso: '123'}}
    end
    result = Result.new
    
    >> result&.data&.[](:address)&.[](:iso)
    => "123"
    

    I think, &.[] is an awkward way of doing it, even if prettier worked as intended. dig method would be preferable here:

    >> result&.data&.dig(:address, :iso)
    => "123"
    >> result = nil
    => nil
    >> result&.data&.dig(:address, :iso)
    => nil
    

    @engineersmnky
    Assuming data hash doesn't actually need safety:

    if result
      result.data[:address][:iso]
    end