Hashes in Ruby and Crystal

April 9, 2019
Hashes in Ruby and Crystal Image Credit: unsplash-logoJon Tyson

Hashes in Ruby and Crystal

Ruby has a ton of different ways to write hashes, particularly ones involving strings or symbols. In addition to the normal explicit syntax, we have:

BASES = Hash['C', 'G', 'G', 'C', 'T', 'A', 'A', 'U']

BASES = ['CGTA','GCAU'].map(&:chars).transpose.to_h

BASES = [%w{C G T A}, %w{G C A U}].transpose.to_h

BASES = %w{C G G C T A A U}.each_cons(2).to_h

BASES = Hash[?C, ?G, ?G, ?C, ?T, ?A, ?A, ?U]

BASES = %w{G C T A}.zip(%w{C G A U}).to_h

BASES = Hash[*%w{C G G C T A A U}]

BASES = Hash[*"CGGCTAAU".chars]

Crystal has somewhat fewer:

BASES = ["CGTA", "GCAU"].map(&.chars).transpose.to_h

BASES = [%w{C G T A}, %w{G C A U}].transpose.to_h

BASES = %w{C G G C T A A U}.each_cons(2).to_h

BASES = Hash.zip(%w{G C T A}, %w{C G A U})

BASES = %w{G C T A}.zip(%w{C G A U}).to_h

Try to avoid using any of these in production code: there’s not a hard line between “clever” and “obfuscated”.

comments powered by Disqus