Techioz Blog

すべての文字と数字のハッシュを生成します

概要

ルビを使用して、アルファベットの各文字 (キー) と 1 ~ 26 (値) のハッシュを作成するにはどうすればよいですか?

キーに「a」から「z」、値に 1 から 26 を使用してハッシュを作成する必要がありますが、自分自身で alphabet = {‘a’=>1,‘b’=>2,… と書きたくないです。 .’y’=>25,‘z’=>26}

alphabet.key?(i) の場合に alphabet[i] を出力するにはコードでこれが必要です

解決策

('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}

手順:

アップデート:

少し難解ですが、これでも機能します

enum = Enumerator.produce('a') {|e| e == 'z' ? raise(StopIteration) : e.succ }.tap do |e| 
  e.define_singleton_method(:[]) {|elem| find_index(elem)&.+(1) } 
  e.define_singleton_method(:to_h) { with_index(1).to_h }
end
enum['w']
#=> 23
enum['W']
#=> nil 
enum.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}