-3

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?

bichanna
  • 954
  • 2
  • 21

1 Answers1

5

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

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Jonne Haß
  • 4,792
  • 18
  • 30