Ruby quick tip: Blocos para fallback em hash lookups
Normalmente, ao tentar fazer um lookup em um hash com uma chave não existente, você tem o seguinte comportamento:
>> h = {:foo => "bar"} => {:foo=>"bar"} >> h[:other_foo] => nil |
Você pode adicionar um bloco para tratar esses casos:
>> h = Hash.new { |hash, key| "#{key} is not here"} => {} >> h[:foo] => "foo is not here" |
É possível, inclusive, alterar o hash em questão:
>> h = Hash.new { |hash, key| hash[key] = "value for #{key}" } => {} >> h[:foo] => "value for foo" |
3 Comentários