如何将用户输入与散列中的值进行比较

时间:2017-04-13 15:07:34

标签: ruby

我正在尝试将用户输入与哈希值中的值进行比较。

例如,如果我在IRB中运行"e".scrabble(),它将在我的哈希值中返回“e”的值。

我想出了如何确定它是否在我的哈希中,以及它是否等于哈希中的一个键。

class String
  define_method(:scrabble) do
    value_for_letters = {
      "A"=> 9,"B" => 2,"C" => 2,"D" => 4,"E" => 12,"F" => 2,
      "G" => 3, "H" => 2, "I" => 9,"J" => 1, "K" => 1,    
      "L" => 4,"M" => 2,"N" => 6,"O" => 8,"P" => 2,"Q" => 1,
      "R" => 6,"S" => 4,"T" => 6,"U" => 4,"V" => 2,"W" => 2,
      "X" => 1,"Y" => 2,"Z" => 1
    }

    value_for_letters.keys().==(self.capitalize())
    "true"
  end
end

1 个答案:

答案 0 :(得分:2)

class String
  LETTER_VALUE_MATCHING = { 
    'A' => 9, 'B' => 2, 'C' => 2, 'D' => 4, 'E' => 12, 
    'F' => 2, 'G' => 3, 'H' => 2, 'I' => 9, 'J' => 1, 
    'K' => 1, 'L' => 4, 'M' => 2, 'N' => 6, 'O' => 8, 
    'P' => 2, 'Q' => 1, 'R' => 6, 'S' => 4, 'T' => 6, 
    'U' => 4, 'V' => 2, 'W' => 2, 'X' => 1, 'Y' => 2, 
    'Z' => 1
  }

  def scrabble
    LETTER_VALUE_MATCHING[self.capitalize]
  end
end

'a'.scrabble
# => 9
'-'.scrabble
# => nil