For the last two weeks I have been working on test driven development (or TDD). It has been a challenging experience working my way through exercise 48 - building a Lexicon.
So far I’ve only written code for the first ‘asser_equal’ in the test provided in the book. Here are the learnings so far:
- Understand the overall problem first, tackle the code later.
- Break the problem down by writing comments in your own words - method known as writing “pseudo code”.
- Hashes aren’t as scary as they seem and I learnt a lot more than what’s in the book by researching into the problem. I took a good look at the ruby docs on hashes found here and here and also arrays.
- You can have blocks inside of blocks, this I didn’t know and just thought I’d try - and it worked!
- Make sure you write a return statement at the end of the block - otherwise the test keeps failing.
Tackling the first two points took me the longest. Once I had that figured out, the coding part became much easier. This is only step one of the problem so far - more to come!
The test was:
test_lexicon.rb
require 'ex48/lexicon.rb'
require "test/unit"
class TestLexicon < Test::Unit::TestCase
def test_directions()
assert_equal(Lexicon.scan("north"), [['direction', 'north']])
result = Lexicon.scan("north south east")
#assert_equal(result, [['direction', 'north'],
['direction', 'south'],
['direction', 'east']])
end
end
The corresponding code that I wrote was:
lexicon.rb
#split sentence/user input into words
#take each of the words and #if word matches the value in the direction hash,
#wrong : return it as an array of array with (word, [[direction, word]]) pairing.
#right: return an array of [value, word]
#right: push this array to the empty mega array of arrays.
#make sure to return result
class Lexicon
@@hash = {
'north' => 'direction',
'south' => 'direction',
'east' => 'direction'
}
def self.scan(sentence)
words = sentence.split
result = []
words.each do |word|
@@hash.each do |key, value|
if key.include?(word)
element = [value, word]
result.push(element)
end
return result
end
end
end
end
comments powered by