0

Here is a test that I am trying to pass:

def test_it_scores_a_double_word_score
    play = Play.new(:word => "hello")
    assert_equal 16, play.score(:word_multiplier => :double)
  end

Here is my class:

class Play < ActiveRecord::Base

  before_save { self.word = word.downcase }

  validates :word, presence: true, length: { maximum: 7 }

  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

  def score(word_multiplier: :single)
    word_multiplier = {:single => 1, :double => 2, :triple => 3}

    word.upcase.chars.inject(0){|sum, letter| sum + letter_scores[letter]} * word_multiplier
  end
end

So my idea is that I need the default value of the hash to be :single. If the key/value pair of :word_multiplier => :double is passed, then I need the the hash to return 2.

I have syntax problems: 1) I have only set defaults in methods using the = sign, not hashes. How does one do this?

2) I put in word_multiplier: :single in the parenthesis which seems to work in setting a default. But :word_multiplier => :single doesn't work. What is going on?

2 Answers 2

1

Why are you using a symbol/enum scheme to set the multiplier? I'd just stick to a number:

def score(word_multiplier = 1)
  word.upcase.chars.inject(0){|sum, letter| sum + letter_scores[letter]} * word_multiplier
end

If you don't pass the method a multiplier, it will default to 1

If you do need to use a hash default parameter, you do it the same way you would any other type:

def my_method(options = {:multiplier => :single})
  multipliers = {:single => 1, :double => 2, :triple => 3}
  word_multiplier = multipliers[options[:multiplier]]
end
Sign up to request clarification or add additional context in comments.

Comments

1

What you're doing is assigning a default to word_multiplier as an argument and then reassigning word_multilier to the hash, without using the argument passed in. The quickest way to fix this, would look like this:

word_multiplier = {:single => 1, :double => 2, :triple => 3}[word_multiplier]

Nb. I'd avoid using the keyword arguments if you want people to use your code until people stop using Ruby 1.8.7 and Ruby 1.9.3.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.