Home > Back-end >  Generate a hash of all letters and digits
Generate a hash of all letters and digits

Time:12-16

Using ruby, how do I make a hash of each letter in the alphabet (keys) and 1-26 (values) ?

I need to create a hash with "a" to "z" in keys and 1 to 26 in values but I do not want to write myself alphabet = {'a'=>1,'b'=>2,....'y'=>25,'z'=>26}

I need this in my code to print alphabet[i] if alphabet.key?(i)

CodePudding user response:

('a'..'z').each.with_index(1).to_h
#=> {"a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5, "f"=>6, "g"=>7, "h"=>8, "i"=>9, "j"=>10, 
#    "k"=>11, "l"=>12, "m"=>13, "n"=>14, "o"=>15, "p"=>16, "q"=>17, "r"=>18, "s"=>19, 
#    "t"=>20, "u"=>21, "v"=>22, "w"=>23, "x"=>24, "y"=>25, "z"=>26}

Steps:

  • ('a'..'z') - create a Range of alphabetic letters "a" through "z" inclusive
  • each - returns an Enumerator
  • with_index(1) - returns an Enumerator of each element of the initial Range combined with its index (starting at 1) e.g. [["a",1],["b",2],...]
  • to_h - convert the Enumerator to a Hash

CodePudding user response:

Hash[('a'..'z').zip(1.upto(26))] 

CodePudding user response:

Depending on requirements you may be able to save memory by using an empty hash with a default proc.

h = Hash.new do |_h,k|
  k.match?(/\A[a-z]\z/) ? (k.ord - 96) : nil
end
h         #=> {}
h['a']    #=>  1
h['z']    #=> 26 
h['R']    #=> nil
h['cat']  #=> nil

See Hash::new and String#match?.

The regular expression reads, "match the beginning of the string (\A) followed by one lowercase letter ([a-z]) followed by the end of the string (\z). [...] is a character class.


If all lowercase letters must comprise the hash's keys one may write the following.

('a'..'z').to_h { |c| [c, c.ord - 96] }
  #=> {"a"=>1, "b"=>2,..., "y"=>25, "z"=>26}

See Enumerable#to_h.

CodePudding user response:

With two ranges, zip and to_h

('a'..'z').zip(1..26).to_h
  • Related