Crystal语言中的.get哈希方法

bic*_*nna -3 python hash dictionary crystal-lang

我有这个Python代码:

# some_dic is a dictionary
value = some_dic.get(var_name, None)
Run Code Online (Sandbox Code Playgroud)

我怎样才能在水晶中做同样的事情?

Jon*_*Haß 5

Python中称为字典的映射类型在Crystal中称为Hash。

可以使用以下方法检索具有显式后备值的值Hash#fetch

numbers = {"Alice" => "0123", "Bob" => "0124"}
puts numbers.fetch("Charlie", "0000")
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下

value = some_dic.fetch(var_name, nil)
Run Code Online (Sandbox Code Playgroud)

如果您的默认值应该是nil那么有一个方便的Hash#[]?方法:

puts numbers["Charlie"]?
Run Code Online (Sandbox Code Playgroud)

在语言简介中阅读有关哈希的更多信息:https://crystal-lang.org/reference/1.3/syntax_and_semantics/literals/hash.html