Search code examples
pythondictionaryhashcrystal-lang

.get method for hash in Crystal language


I have this Python code:

# some_dic is a dictionary
value = some_dic.get(var_name, None)

How can I do the same in Crystal?


Solution

  • The map type called dictionary in Python is called Hash in Crystal.

    Values with an explicit fallback value can be retrieved using the Hash#fetch method:

    numbers = {"Alice" => "0123", "Bob" => "0124"}
    puts numbers.fetch("Charlie", "0000")
    

    So in your case

    value = some_dic.fetch(var_name, nil)
    

    If your default value should be nil then there's the handy Hash#[]? method:

    puts numbers["Charlie"]?
    

    Read more about hashes in the language introduction: https://crystal-lang.org/reference/1.3/syntax_and_semantics/literals/hash.html