1

I'm trying to compare user input to values in my hash.

For example, if I ran "e".scrabble() in IRB, it would return the value for "e" in my hash.

I figured out how to identify if it's in my hash and if it's equal to one of the keys in the hash.

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
2
  • 1
    I simply reformatted your code slightly to conform with the Ruby convention of indenting two spaces. There are two things I found a bit odd with your code: that you chose to use define_method rather than simply def scrabble... and that you invoked the method String#== in the formal way (.==(...)), rather than using the "syntactic sugar" keys() == self.capitalize (the extra parens are not necessary, btw). I suspect that's what you are being taught in your early days of learning Ruby, which is a very good thing! You will learn the conventional methods soon enough. Commented Apr 13, 2017 at 15:35
  • thanks for the tips @CarySwoveland Commented Apr 13, 2017 at 15:47

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

self is redundant and an umlaut is not well recognizable, which made me “wtf?” for a while. Here is some more evident Cyrillic: “Щ” :)
@mudasobwa "💩".scrabble
@Jordan even better, indeed.
Bonus track: count a word value "abc".split('').map(&:scrabble).reduce(:+).

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.