Manasi Salvi

TDD Lesson 3

The next challenge was writing the code for the test: test_lexicon.rb

	def test_numbers()
	    assert_equal(Lexicon.scan("1234"), [['number', 1234]])
	    result = Lexicon.scan("3 91234")
	    assert_equal(result, [['number', 3],
	           ['number', 91234]])
	end
 

The test requires conversion the scanned input in the form of a sentence into numbers. This required the use of exceptions by using the begin-rescue statement. Exceptions indicate that something has gone wrong and therefore throws an error - in this case an Argument Error. Before using the exceptions I did try to put the numbers into the hash (as for the rest of the word types) and looping over this hash however this wouldn’t work because it would try to convert some of the words into numbers and throw back an error. This would also be impractical as it wouldn’t be able to handle every possible combination of numbers e.g. the input could look like [‘12345’, ‘0’, ‘12’] and so on.

With the use of the exceptions I came up with the folowing code:

 	def self.convert_integer(word) #scan self and convert to integer - this becomes the number variable
  		number = /[0-9]/ #define the number as an integer between 0-9
  		begin
    		return Integer(word) 
  		rescue  #Argument error thrown when the word is not an integer
    		return nil
  		end
	end

comments powered by Disqus