scrabble_score.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Compute scrabble score for a word
class Scrabble
  LETTER_SCORES = {
    'A' => 1, 'B' => 3, 'C' => 3,  'D' => 2, 'E' => 1, 'F' => 4, 'G' => 2,
    'H' => 4, 'I' => 1, 'J' => 8,  'K' => 5, 'L' => 1, 'M' => 3, 'N' => 1,
    'O' => 1, 'P' => 3, 'Q' => 10, 'R' => 1, 'S' => 1, 'T' => 1, 'U' => 1,
    'V' => 4, 'W' => 4, 'X' => 8,  'Y' => 4, 'Z' => 10
  }.freeze

  def initialize(word)
    @score = Scrabble.score(word)
  end

  attr_reader :score

  # Convenience scoring
  def self.score(word)
    word ? word_score(word) : 0
  end

  class << self
    private

    # Calculate score for a word
    def word_score(word)
      word.upcase.chars.map { |c| LETTER_SCORES[c] }.compact.reduce(0, &:+)
    end
  end
end

@remcopeereboom thinks this looks great

Comments


You're not logged in right now. Please login via GitHub to comment