DEV Community

Discussion on: What's the difference? Ruby vs. Python

Collapse
 
marcosvafilho profile image
Marcos Filho

Great article, thanks for that.

You probably already know that, but you can also write Ruby hashes in a similar notation to Python dictionaries:

# Ruby hash 
hex_colors = { white: '#FFFFFF', grey_light: '#CCCCCC',  grey_dark: '#333333', black: '#000000' }
puts(hex_colors[:black]) # #000000

Some caveats when using this notation though:

  • no hash keys beginning with a number (because they are symbols)
# invalid Ruby hash
numbers = { 1: 'one', 2: 'two', 3: 'three'}

# valid Ruby hash (no need to use quotes)
numbers = { one: 1, two: 2, three: 3}
  • fetching a value from a key requires using a symbol:
hex_colors = { white: '#FFFFFF', grey_light: '#CCCCCC',  grey_dark: '#333333', black: '#000000' }

# valid notation to fetch values
hex_colors[:black] # returns #000000

# invalid notation to fetch values
hex_colors['black'] # returns nil