Given a word, compute the scrabble score for that word.
You'll need these:
Letter Value A, E, I, O, U, L, N, R, S, T 1 D, G 2 B, C, M, P 3 F, H, V, W, Y 4 K 5 J, X 8 Q, Z 10
"cabbage" should be scored as worth 14 points:
And to total:
3 + 2*1 + 2*3 + 2 + 1
3 + 2 + 6 + 3
5 + 9
For installation and learning resources, refer to the Ruby resources page.
For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:
gem install minitest
If you would like color output, you can
require 'minitest/pride' in
the test file, or note the alternative instruction, below, for running
the test file.
Run the tests from the exercise directory using the following command:
To include color from the command line:
ruby -r minitest/pride scrabble_score_test.rb
Inspired by the Extreme Startup game https://github.com/rchatley/extreme_startup
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
require 'minitest/autorun' require_relative 'scrabble_score' class ScrabbleTest < Minitest::Test def test_empty_word_scores_zero assert_equal 0, Scrabble.new('').score end def test_whitespace_scores_zero skip assert_equal 0, Scrabble.new(" \t\n").score end def test_nil_scores_zero skip assert_equal 0, Scrabble.new(nil).score end def test_scores_very_short_word skip assert_equal 1, Scrabble.new('a').score end def test_scores_other_very_short_word skip assert_equal 4, Scrabble.new('f').score end def test_simple_word_scores_the_number_of_letters skip assert_equal 6, Scrabble.new('street').score end def test_complicated_word_scores_more skip assert_equal 22, Scrabble.new('quirky').score end def test_scores_are_case_insensitive skip assert_equal 41, Scrabble.new('OXYPHENBUTAZONE').score end def test_convenient_scoring skip assert_equal 13, Scrabble.score('alacrity') end end
=begin Write your code for the 'Scrabble Score' exercise in this file. Make the tests in `scrabble_score_test.rb` pass. To get started with TDD, see the `README.md` file in your `ruby/scrabble-score` directory. =end class Scrabble def initialize(input) @input = input || '' end def self.score(input) new(input).score end def score @input.split('').reduce(0) do |total_score, character| total_score += score_value(character.downcase) end end def score_value(character) return 1 if /[aeioulnrst]/.match?(character) return 2 if /[dg]/.match?(character) return 3 if /[bcmp]/.match?(character) return 4 if /[fhvwy]/.match?(character) return 5 if /[k]/.match?(character) return 8 if /[jx]/.match?(character) return 10 if /[qz]/.match?(character) 0 end end
I chose to use regex matching to solve this rather than putting together a score-table hash, but there might be a way to use that to get the overall length down. I also suspect that there's a way to condense my `score_value` method.