HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Letter-scoring Scrabble class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
letterscoringclassscrabble

Problem

I wrote Ruby code (copied below) but was told that the code does not compile (it does on my computer) and that it does not answer the question:


Create a class called Scrabble that implements a method called score that accepts one word as a parameter and returns the scrabble score associated with that word

The code compiles on my computer and provides the response that I believe was required. Can anyone point out issues with the code quality? I realize I did not write any unit tests for this code.

I could add more inline comments in the code (I added comments at the top of the class which I removed from the code I copied here).

class Scrabble

  attr_reader :word

  def initialize(word)
    @word = word
  end

  def score
    letters = word.upcase.split('')

    total = 0
    letters.each do |letter|
      total += letter_scores[letter]
    end

    total
  end

# scores for each letter
  def 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
    }
  end
end

puts "Type in one word for scrabble scorer"
word = gets.chomp
puts "Scrabble score for " + word + " is " + Scrabble.new(word).score.to_s

Solution

Some comments:

-
score method: With functional - instead of imperative - style, you'll get write more compact code.

-
You may use the abstraction Hash#values_at.

-
letter_scores is constant. It can be a class constant, then.

-
String interpolation: Use "#{var} = #{value}" style.

-
[edit] As you say, word should be an argument of score, not the class initializer.

I'd write:

class Scrabble
  LETTER_SCORES = {...}

  def score(word)
    scores = LETTER_SCORES.values_at(*word.upcase.chars)
    scores.compact.reduce(0, :+)
  end
end

scrabble = Scrabble.new
puts("Type in one word for scrabble scorer:")
word = gets.strip
puts("Scrabble score for #{word} is #{scrabble.score(word)}")

Code Snippets

class Scrabble
  LETTER_SCORES = {...}

  def score(word)
    scores = LETTER_SCORES.values_at(*word.upcase.chars)
    scores.compact.reduce(0, :+)
  end
end

scrabble = Scrabble.new
puts("Type in one word for scrabble scorer:")
word = gets.strip
puts("Scrabble score for #{word} is #{scrabble.score(word)}")

Context

StackExchange Code Review Q#101934, answer score: 5

Revisions (0)

No revisions yet.