I am struggling finding a way to verify these methods and was wondering if anyone knew a basic way to do this?
class PigLatinTest < MiniTest::Unit::TestCase
def test_word_beginning_with_a
assert_equal "appleay", PigLatin.translate("apple")
end
def test_other_word_beginning_e
assert_equal "earay", PigLatin.translate("ear")
end
def test_word_beginning_with_p
assert_equal "igpay", PigLatin.translate("pig")
end
For example the first one might be:
module PigLatin
class Word
def initialize(word)
@word = word.to_s
end
# remember to use the .to_s method
def translate(word)
if word[0] == "a" || "e" || "o" || "u" || "i"
word = word + "ay"
elsif word[0] != "a" || "e" || "o" || "u" || "i"
word = word-word[0]+"ay"
end
end
end
# you can add method here even outside of the class ...
end
------------in another file
module PigLatin
class Word
# remember to use the .to_s method
end
# you can add method here even outside of the class ...
end
Your
translate
method won't work. The problem is here:and
You can't compare that way as the right side of either will not do what you think it will.
Some simple checks will show why there's something wrong:
Why are those wrong? Let's look at what's happening:
When the word starts with 'a', the test
'a' == 'a'
is true:If we
||
("or") true and something, we get true back because it was the first "true" value seen:If the first test failed, then
||
causes the second test to be evaluated, which in your code was"e"
, and wasn't a test, but Ruby didn't know that, and thought it was a "true" return value so it became the result of the expression:Knowing that, a correct way to write this would be:
however, that rapidly becomes hard to read and unwieldy, so something more concise is needed:
There is a problem with this though; As the array size increases, more loops are required to compare to the
[0]
value, which slows the code unnecessarily. A regular expression, written correctly, can get rid of that looping so the speed stays very constant:Notice though, that instead of getting true/false, the results are the character matched by the pattern or nil. In Ruby, only nil and false are considered false values, and everything else is true, so we can translate those into true, true, true, false respectively, but by taking advantage of the
!
operator we can make it even more clear:It might seem that we'd have to use
!!!
to "not" the results like we'd want when using!=
, but that isn't necessary. A single!
will do the same thing:But wait! There's more! Even that can be improved upon a slight amount by removing the string slice (
[0]
) and using a regex anchor. Compare these two, and their benchmark:So, using something like:
will be fast and compact and let you test to see what a string starts with.