Code Katas: Kicking off With a Little JavaScript

BEWARE, this is a crazy long post. So before you jump in for a read, just know that it isn’t a two minute read. 😉

A few days ago, my friend Aeden Jameson (@daliful) asks, “you want to work through a code kata this weekend?” I thought, well yeah, that’d be cool. So we met at Cafe Fiore and hacked out the beginning of a Kata based on the Roman to Arabic and Arabic to Roman Numerals. It was fun, which led me to working up an actual blog entry related to our kata session. This however, is just me working through a similar aspect of the numeral conversions with JavaScript. Enjoy.

First things first, I’m using QUnit which is available on Github with documentation on the jQuery Site. So if you’re going to work through these, go get that first. Or use another unit testing framework. I also am using Webstorm, which is a pretty sweet IDE for editing HTML, CSS, and JavaScript available from Jetbrains. You can even do scary stuff like edit and write PHP! Oh yeah that’s right! It IS absolutely worth the money. 😀

With that out of the way, here’s what I started with. First I created a QUnit and Scripts Directory. In QUnit I placed the qunit.css and qunit.js files and in the Scripts Directory I added the jquery-1.5.1.min.js file. The later file isn’t that important at this point, but I’ve added it since I intend to use it at some point later on.

There are a few main ideas behind doing a Code Kata:

  • Keep the implementation code to the absolute minimum needed to pass the test.
  • Use a steady TDD/BDD Style testing first approach to think through each step.

[sourcecode language=”html”]
<!DOCTYPE HTML>
<html>
<head>
<title>TimePiece Object Unit Tests</title>
<link rel="stylesheet"
href="../QUnit/qunit.css"
type="text/css"
media="screen"/>
<script type="text/javascript"
src="../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript"
src="../QUnit/qunit.js"></script>
<script type="text/javascript">
// All the code bits go here!
</script>
<body>
<p>Roman to Arabic, Arabic to Roman…</p>
<span>QUnit Test Results…</span>

<h1 id="qunit-header">Numeral Conversions</h1>

<h2 id="qunit-banner"></h2>

<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">hidden text</div>
</body>
</html>
[/sourcecode]

Which gets me to the point that I have a rendering of an empty test results page, as shown below.

QUnit Test Results Page
QUnit Test Results Page

The next step was to get started. So jumping right in I got some code put in place for a failing test.

[sourcecode language=”JavaScript”]
module("When converting an integer into a roman numeral");

test("should receive I when passing a 1", function() {
equal(NumeralConverter.get_arabic_numeral("I"), 1, "I was returned when 1 was passed as a parameter.");
});
[/sourcecode]

Red light received, code committed, implementing for green.

[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
return 1;
}
}
[/sourcecode]

Code committed. Sticking with the idea to implement the bare minimum needed, one can see pretty obviously that this isn’t much of a converter. So going forward I added the next test, for our second numeral.

[sourcecode language=”JavaScript”]
test("should receive 2 when passing a ‘II’", function() {
equal(NumeralConverter.get_arabic_numeral("II"), 2, "2 was returned when ‘II’ was passed as a parameter.");
});
[/sourcecode]

Again, nothing really specific here, nor is any defined logic really visible in what the method is needing to do. So after the commit I implemented the logic to pass this and committed this also.

[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
var result = romanNumeral == "I" ? 1 : 2;
return result;
}
}
[/sourcecode]

That gets those bits passing. With a nice little JavaScript Ternary Operator. Still not hitting on the big picture of converting between the roman to arabic numerals yet, but we’re getting a little closer. Stepping up to the next test, pretty much more of the same.

[sourcecode language=”JavaScript”]
test("should receive 3 when passing a ‘III’", function() {
equal(NumeralConverter.get_arabic_numeral("III"), 3, "3 was returned when ‘III’ was passed as a parameter.");
});
[/sourcecode]

With the failing test committed, I did what seems like the easiest solution, yet so much like it is cheating. But hey! It works! That’s what is is about and one ever knows what kind of alternate solutions will crop up! Think small steps and things will lay out for you in interesting ways. Discipline!

[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
return romanNumeral.length;
}
}
[/sourcecode]

So now the first tricky one comes up, the IV. The test continues to repeat. I pondered a rowset style test, but wasn’t really happy with any of the prospective solutions I saw with a quick search on the net for qunit. So on with tests as I’ve been going.

[sourcecode language=”JavaScript”]
test("should receive 4 when passing a ‘IV’", function() {
equal(NumeralConverter.get_arabic_numeral("IV"), 4, "4 was returned when ‘IV’ was passed as a parameter.");
});
[/sourcecode]

Red light received, code committed. The implementation for this, still feels like cheating. Simplest code to get the test passing possible.

[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
if(romanNumeral == "IV"){
return 4;
}
return romanNumeral.length;
}
}
[/sourcecode]

Green light, code committed. Again, straight into a test.

[sourcecode language=”JavaScript”]
test("should receive 5 when passing a ‘V’", function() {
equal(NumeralConverter.get_arabic_numeral("V"), 5, "5 was returned when ‘V’ was passed as a parameter.");
});
[/sourcecode]

Red light, code committed.

[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
if(romanNumeral == "IV"){
return 4;
}
else if(romanNumeral == "V"){
return 5;
}
return romanNumeral.length;
}
}
[/sourcecode]

Green light. Code committed. It seems like something is starting to brew up out of the method.

[sourcecode language=”JavaScript”]
test("should receive 6 when passing a ‘VI’", function() {
equal(NumeralConverter.get_arabic_numeral("VI"), 6, "6 was returned when ‘VI’ was passed as a parameter.");
});
[/sourcecode]

Red light. Code committed.

[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
if(romanNumeral == "IV"){
return 4;
}
else if(romanNumeral == "V"){
return 5;
}
else if(romanNumeral == "VI"){
return 6;
}
return romanNumeral.length;
}
}
[/sourcecode]

Green light, code committed. I implemented the next bits, but at testing that VIII returns 8 I began a refactoring. If I were to split the one Roman Numerals ‘I’ off I could then just count their length and add them to the five Roman Numeral V. I didn’t really think about how that would work past 8, but it seemed like a valid refactoring. After that, these two additional tests were completed and passing.

[sourcecode language=”JavaScript”]
test("should receive 7 when passing a ‘VII’", function() {
equal(NumeralConverter.get_arabic_numeral("VII"), 7, "7 was returned when ‘VII’ was passed as a parameter.");
});

test("should receive 8 when passing a ‘VIII’", function() {
equal(NumeralConverter.get_arabic_numeral("VIII"), 8, "8 was returned when ‘VIII’ was passed as a parameter.");
});
[/sourcecode]

The actual method implementation looked like this now.

[sourcecode language=”JavaScript”]
var NumeralConverter = {
get_arabic_numeral : function ( romanNumeral ){
var ones = 0;
var five = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length -1;
var iCount = romanNumeral.split(/I/g).length – 1;

if(romanNumeral == "IV"){
return 4;
}
else if(vCount > 0){
five = vCount * 5;
}

ones = iCount;
result = five + ones;

return result;
}
}
[/sourcecode]

Now we’re actually getting some logic in there. If one breaks the rules, there is even a bit of foreshadowing to where the logic and looping will eventually end up. But I’m going to keep going with the KISS idea and doing a minimal implement for each failing test! Moving right along…

[sourcecode language=”JavaScript”]
test("should receive 9 when passing a ‘IX’", function() {
equal(NumeralConverter.get_arabic_numeral("IX"), 9, "9 was returned when ‘IX’ was passed as a parameter.");
});
[/sourcecode]

Ok, ok, now at this point I’m thinking, “oh jeez, this list of tests looks like a mess. These need refactored now.” I did look for a rowtest earlier, and that didn’t exist really. So something else ought to work though, but the question is what? So I looked around and just took a few minutes to think. Take a look at the tests at this point all listed together.

[sourcecode language=”JavaScript”]
module("When converting a roman numeral into an arabic numeral");

test("should receive 1 when passing a ‘I’", function() {
equal(NumeralConverter.get_arabic_numeral("I"), 1, "1 was returned when ‘I’ was passed as a parameter.");
});

test("should receive 2 when passing a ‘II’", function() {
equal(NumeralConverter.get_arabic_numeral("II"), 2, "2 was returned when ‘II’ was passed as a parameter.");
});

test("should receive 3 when passing a ‘III’", function() {
equal(NumeralConverter.get_arabic_numeral("III"), 3, "3 was returned when ‘III’ was passed as a parameter.");
});

test("should receive 4 when passing a ‘IV’", function() {
equal(NumeralConverter.get_arabic_numeral("IV"), 4, "4 was returned when ‘IV’ was passed as a parameter.");
});

test("should receive 5 when passing a ‘V’", function() {
equal(NumeralConverter.get_arabic_numeral("V"), 5, "5 was returned when ‘V’ was passed as a parameter.");
});

test("should receive 6 when passing a ‘VI’", function() {
equal(NumeralConverter.get_arabic_numeral("VI"), 6, "6 was returned when ‘VI’ was passed as a parameter.");
});

test("should receive 7 when passing a ‘VII’", function() {
equal(NumeralConverter.get_arabic_numeral("VII"), 7, "7 was returned when ‘VII’ was passed as a parameter.");
});

test("should receive 8 when passing a ‘VIII’", function() {
equal(NumeralConverter.get_arabic_numeral("VIII"), 8, "8 was returned when ‘VIII’ was passed as a parameter.");
});

test("should receive 9 when passing a ‘IX’", function() {
equal(NumeralConverter.get_arabic_numeral("IX"), 9, "9 was returned when ‘IX’ was passed as a parameter.");
});
[/sourcecode]

That’s a lot of tests. Well, I looked through the documentation a little bit, and realized that I could just do this. Is it more readable? It almost comes off as rowset tests in junit/nunit.

[sourcecode language=”JavaScript”]
module("When converting a roman numeral into an arabic numeral");

test("should receive arabic numeral", function() {
equal(NumeralConverter.get_arabic_numeral("I"), 1, "1 when ‘I’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("II"), 2, "2 when ‘II’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("III"), 3, "3 when ‘III’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("IV"), 4, "4 when ‘IV’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("V"), 5, "5 when ‘V’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("VI"), 6, "6 when ‘VI’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("VII"), 7, "7 when ‘VII’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("VIII"), 8, "8 when ‘VIII’ was passed as a parameter.");
equal(NumeralConverter.get_arabic_numeral("IX"), 9, "9 when ‘IX’ was passed as a parameter.");
});
[/sourcecode]

Either way, I’m sticking to it for now. I added the test for X.

[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("X"), 10, "10 when ‘X’ is passed in.");
[/sourcecode]

Then implemented it following a similar pattern that I had already started.

[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;

if (romanNumeral == "IV") {
return 4;
}
else if (romanNumeral == "IX") {
return 9;
}
else if (vCount > 0) {
fives = vCount * 5;
}
else if (xCount > 0) {
tens = xCount * 10;
}

ones = iCount;
result = fives + ones + tens;

return result;
}
[/sourcecode]

That was easy enough. Also note, when the pattern that is now evident among the logic, the next two tests automatically pass. Now some real progress has been made.

[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("XI"), 11, "11 when ‘XI’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XII"), 12, "12 when ‘XII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XIII"), 13, "13 when ‘XIII’ is passed in.");
[/sourcecode]

Now however, things get a bit tricky. Add a test for ‘VX’.

[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("VX"), 14, "14 when ‘VX’ is passed in.");
[/sourcecode]

So adding another simple exception, pretty much takes care of that.

[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;

if (romanNumeral == "IV") {
return 4;
}
else if (romanNumeral == "IX") {
return 9;
}
else if(romanNumeral == "VX") {
return 14;
}
else if (vCount > 0) {
fives = vCount * 5;
}
else if (xCount > 0) {
tens = xCount * 10;
}

ones = iCount;
result = fives + ones + tens;

return result;
}
[/sourcecode]

Now that trickiness comes up when adding the test for ‘XV’.

[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("XV"), 15, "15 when ‘XV’ is passed in.");
[/sourcecode]

Red light, code commit. Now to implement. An actual reduction of code gets us back in action here.

[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;

if (romanNumeral == "IV") {
return 4;
}
else if (romanNumeral == "IX") {
return 9;
}
else if (romanNumeral == "VX") {
return 14;
}
else if (vCount > 0 || xCount > 0) {
fives = vCount * 5;
tens = xCount * 10;
}

ones = iCount;
result = fives + ones + tens;

return result;
}
[/sourcecode]

Green light. Code Commit. Now for the next three tests, they’ll all pass. The next test that we run into that gives us a failing test is for 19, or ‘XIX’. For the tests below I went ahead and added XVI, XVII, and XVIII.

[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("XVI"), 16, "16 when ‘XVI’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XVII"), 17, "17 when ‘XVII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XVIII"), 18, "18 when ‘XVIII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XVIII"), 19, "19 when ‘XIX’ is passed in.");
[/sourcecode]

Red light, code commit.

[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;

if (romanNumeral == "IV") {
return 4;
}
else if (romanNumeral == "IX") {
return 9;
}
else if (romanNumeral == "VX") {
return 14;
}
else if (romanNumeral == "XIX") {
return 19;
}
else if (vCount > 0 || xCount > 0) {
fives = vCount * 5;
tens = xCount * 10;
}

ones = iCount;
result = fives + ones + tens;

return result;
}
[/sourcecode]

Green light, code commit. Add the test for ‘XX’ and you’ll find that this test automatically passes also. There’s still soemthing to be done about the odd else if assigned values above! But onward. After the test for ‘XX’, I’ll jump right in and see how far I can get. Not until 24 do I run into an issue.

[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("XXI"), 21, "21 when ‘XXI’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XXII"), 22, "22 when ‘XXII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XXIII"), 23, "23 when ‘XXIII’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("XXIV"), 24, "24 when ‘XXIV’ is passed in.");
[/sourcecode]

It seems like there is some type of logic happening, some repeatable logic. So I started giving it a good look over. I will admit, I went ahead and worked through several more of the tests and implementation details just to force more of the if else statements to be apparent. I added tests for 25-30 and implemented passing tests with the following code.

[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;

if (romanNumeral == "IV") {
return 4;
}
else if (romanNumeral == "IX") {
return 9;
}
else if (romanNumeral == "XIV") {
return 14;
}
else if (romanNumeral == "XIX") {
return 19;
}
else if (romanNumeral == "XXIV") {
return 24;
}
else if (romanNumeral == "XXIX") {
return 29;
}
else if (vCount > 0 || xCount > 0) {
fives = vCount * 5;
tens = xCount * 10;
}

ones = iCount;
result = fives + ones + tens;

return result;
}
[/sourcecode]

I started to stop and do research, look up some other functions that already do this. I wanted to bad, but I stuck with the original idea behind the Kata. Just implement the bare minimum code and go through the red, green, refactor approach. In the end I stuck with that approach and came up with this mess.

[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;

if (vCount > 0 || xCount > 0) {
fives = vCount * 5;
tens = xCount * 10;
}

if (romanNumeral.length > 1) {
if (romanNumeral == "IV" || romanNumeral == "IX") {
var workingNumber = fives + tens – iCount;
return workingNumber;
}
else if (romanNumeral == "XIV") {
return 14;
}
else if (romanNumeral == "XIX") {
return 19;
}
else if (romanNumeral == "XXIV") {
return 24;
}
else if (romanNumeral == "XXIX") {
return 29;
}
}

ones = iCount;
result = fives + ones + tens;

return result;
}
[/sourcecode]

From here, I had to get the IV or IX off of the larger roman numerals. I needed some string capabilties, so I pulled in some libraries for string manipulation, namely the Underscore.js + Underscore.string libraries. After that refactor, I knocked out all the code (yup, deleting code!) around the extra else if statements.

[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;

if (vCount > 0 || xCount > 0) {
fives = vCount * 5;
tens = xCount * 10;
}

if (romanNumeral.length > 1) {
if (_(romanNumeral).endsWith("IV") || _(romanNumeral).endsWith("IX")) {
var workingNumber = fives + tens – iCount;
return workingNumber;
}
}

ones = iCount;
result = fives + ones + tens;

return result;
}
[/sourcecode]

At this point I was fairly confident that I had a huge number of effective conversions. So I decided to skip a few tests and head into the other numbers and other exception criteria. I did a commit for the refactor that I just finished and then jumped into a test for L, the Roman Numeral which represents 50, and the other numbers M, D, and C. I did write these individually, and then added the code, but I’ve added them altogether here to conserve space in this already long blog entry. 😉

[sourcecode language=”JavaScript”]
equal(NumeralConverter.get_arabic_numeral("L"), 50, "50 when ‘L’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("M"), 1000, "1000 when ‘M’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("D"), 500, "500 when ‘D’ is passed in.");
equal(NumeralConverter.get_arabic_numeral("C"), 100, "100 when ‘C’ is passed in.");
[/sourcecode]

Red light, committed code. Implement.

[sourcecode language=”JavaScript”]
get_arabic_numeral : function (romanNumeral) {
var ones = 0, fives = 0, tens = 0, fifties = 0;
var hundreds = 0, fiveHundreds = 0, thousands = 0;
var result = 0;
var vCount = romanNumeral.split(/V/g).length – 1;
var iCount = romanNumeral.split(/I/g).length – 1;
var xCount = romanNumeral.split(/X/g).length – 1;
var lCount = romanNumeral.split(/L/g).length – 1;
var cCount = romanNumeral.split(/C/g).length – 1;
var dCount = romanNumeral.split(/D/g).length – 1;
var mCount = romanNumeral.split(/M/g).length – 1;

if (vCount > 0 || xCount > 0 || lCount > 0 || cCount > 0 || dCount > 0 || mCount > 0) {
fives = vCount * 5;
tens = xCount * 10;
fifties = lCount * 50;
hundreds = cCount * 100;
fiveHundreds = dCount * 500;
thousands = mCount * 1000;
}

if (romanNumeral.length > 1) {
if (_(romanNumeral).endsWith("IV") || _(romanNumeral).endsWith("IX")) {
var workingNumber = fives + tens – iCount;
return workingNumber;
}
}

ones = iCount;
result = ones + fives + tens + fifties + hundreds + fiveHundreds + thousands;

return result;
}
[/sourcecode]

At this point, one can see some of the changes from refactoring, and the practice of TDD for this specific kata. It is a great way to become more efficient at thinking in a TDD way, or a touch of how one might do BDD. I hope to have more blog entries about BDD vs. TDD, how to do this, and how to get better at it. Of course, I can only write about what I know or am learning myself, and with this particular occupation I’m always learning. 😉

Hopefully this was useful, as material and as an idea. I’m not 100% finished with this kata, and I will post the code in its completed form once I’m done. For now, enjoy, and practice that TDD/BDD awesomeness!

A Zillion Ruby Kōans

NOTE: Because of formatting, I couldn’t have a curly bracket with a colon and an “o” or it turns up with some unavailable WordPress Emoticon URI. So thus I have changed items with this naming to :z_one and :z_two respectively.

Yup, still moving through all the Ruby Koans. There are, after all 276 of these things! 😉 So no more yapping, onto the notes and green lighting the tests. Cheers!

[sourcecode language=”ruby”]
def test_creating_hashes
empty_hash = Hash.new
assert_equal Hash, empty_hash.class
assert_equal({ }, empty_hash)
assert_equal 0, empty_hash.size
end

def test_hash_literals
hash = { :z_one => "uno", :z_two => "dos" }
assert_equal 2, hash.size
end

def test_accessing_hashes
hash = { :z_one => "uno", :z_two => "dos" }
assert_equal "uno", hash[:z_one]
assert_equal "dos", hash[:z_two]
assert_equal nil, hash[:doesnt_exist]
end
[/sourcecode]

From test_creating_hashes a Hash.new or {} both appear to create a new empty hash object. The second test creates and adds values to the hash. The third test has asserts that verify the data is inserted in the positions that are expected.

[sourcecode language=”ruby”]
def test_changing_hashes
hash = { :z_one => "uno", :z_two => "dos" }
hash[:z_one] = "eins"

expected = { :z_one => "eins", :z_two => "dos" }
assert_equal true, expected == hash

# Bonus Question: Why was "expected" broken out into a variable
# rather than used as a literal?
end
[/sourcecode]

Again, the hash is setup into the hash variable. Then the expected is setup in another variable. Since Ruby is pointer oriented, the expected variable is setup identical to the hash variable to assure that they truly are identical.

[sourcecode language=”ruby”]
def test_hash_is_unordered
hash1 = { :z_one => "uno", :z_two => "dos" }
hash2 = { :z_two => "dos", :z_one => "uno" }

assert_equal true, hash1 == hash2
end

def test_hash_keys
hash = { :z_one => "uno", :z_two => "dos" }
assert_equal 2, hash.keys.size
assert_equal true, hash.keys.include?(:z_one)
assert_equal true, hash.keys.include?(:z_two)
assert_equal Array, hash.keys.class
end

def test_hash_values
hash = { :z_one => "uno", :z_two => "dos" }
assert_equal 2, hash.values.size
assert_equal true, hash.values.include?("uno")
assert_equal true, hash.values.include?("dos")
assert_equal Array, hash.values.class
end
[/sourcecode]

test_hash_is_unordered shows that a hash, no matter the order the values are assigned, assigns them to the values that are directly set to.

[sourcecode language=”ruby”]
def test_combining_hashes
hash = { "jim" => 53, "amy" => 20, "dan" => 23 }
new_hash = hash.merge({ "jim" => 54, "jenny" => 26 })

assert_equal true, hash != new_hash

expected = { "jim" => __, "amy" => 20, "dan" => 23, "jenny" => __ }
assert_equal false, expected == new_hash
end
[/sourcecode]

This test asserts that the two different hashes are different, nothing amazing or odd there. The second part asserts that the next and expected hashes are different. Which again, is what we expect.

[sourcecode language=”ruby”]
def test_default_value
hash1 = Hash.new
hash1[:z_one] = 1

assert_equal 1, hash1[:z_one]
assert_equal nil, hash1[:z_two]

hash2 = Hash.new("dos")
hash2[:z_one] = 1

assert_equal 1, hash2[:z_one]
assert_equal "dos", hash2[:z_two]
end
[/sourcecode]

This test confirms that a hash with a request against a hash position that isn’t assigned to yet returns nil. The later two asserts show that a number compared to the hash position that contains a number compares as a number, and a string compared to a position that has a string also compares as equal.

Until next time, hack some koans.

Kōans of Code

I’ve continued the Kōans, but there is one thing that won’t be noticeable from this blog entry. I however wanted to mention it. The first blog entry was worked through on an OS-X Apple Machine, the second on an Ubunta Linux Machine, and now I’m heading for this blog entry to be completed with  Windows 7. It is of course completely irrelevant, but at the same time very relevant.  🙂 But enough about operating system awesomeness. Let’s take a look at the new gazillion Kōans that caught my note taking.

[sourcecode language=”ruby”]
class AboutArrays < EdgeCase::Koan
def test_creating_arrays
empty_array = Array.new
assert_equal Array, empty_array.class
assert_equal 0, empty_array.size
end
[/sourcecode]

Easy peasy. Array.new creates a new empty array. Got it. An Array is the class type retrieved when calling empty_array.class. Got it. The empty array has a size of zero, Got it.

[sourcecode language=”ruby”]
def test_array_literals
array = Array.new
assert_equal [], array

array[0] = 1
assert_equal [1], array

array[1] = 2
assert_equal [1, 2], array

array << 333
assert_equal [1, 2, 333], array
end
[/sourcecode]

Ok, this one has some interesting bits in it. Having array[0] and array[1] assigned to a value of 1 and 2 seems standard operating practice for a language. This dual chevrons pointing into the array thing is a little more unique. This operator appears to take the value on the right, and put it onto the array’s stack. Simply, the double kick operator (or whatever it is called) puts the value on the next available array index position. Ok, cool. Got it.

[sourcecode language=”ruby”]
def test_accessing_array_elements
array = [:peanut, :butter, :and, :jelly]

assert_equal :peanut, array[0]
assert_equal :peanut, array.first
assert_equal :jelly, array[3]
assert_equal :jelly, array.last
assert_equal :jelly, array[-1]
assert_equal :butter, array[-3]
end
[/sourcecode]

Alright, got an array with 4 elements in it. First assert confirms that :peanut is the returned value from the first element in the array. The array.first call functionally does the same thing. The third assert gets the 3rd value in the array, keeping in mind a zero based index for the array, that gives us the 4th actual item in the list of items stored within the array. I love it, standard programmer weirdness. Why do programmers start with zero when nobody on earth starts a “list” of items with a zero. Blagh, whatever, that’s the reality of it. (That was, in a sense, somewhat rhetorical, I get the underlying reasons but that doesn’t help explain a zero based index to initial non-programmers.)

[sourcecode language=”ruby”]
def test_slicing_arrays
array = [:peanut, :butter, :and, :jelly]

assert_equal [:peanut], array[0,1]
assert_equal [:peanut, :butter], array[0,2]
assert_equal [:and, :jelly], array[2,2]
assert_equal [:and, :jelly], array[2,20]
assert_equal [], array[4,0]
assert_equal [], array[4,100]
assert_equal nil, array[5,0]
end
[/sourcecode]

Slicing arrays again with the PB & J. With two values, the first thing I notice is that this is no multidimensional array. Two values within the square brackets means that you have a starting position and then a value of how many to retrieve. If there is a value like the fourth asset, starting at the 2nd position (3rd actual value) and taking the next 20 elements, basically retrieves whatever values are available, which in this case gets us 2 elements.

Now, I’m a slight bit perplexed though as to why nil is returned for something request nothing from the 5th starting point of the array versus the same being requested from the 4th starting point in the array. I’ll have to read up on that…

[sourcecode language=”ruby”]
def test_arrays_and_ranges
assert_equal Range, (1..5).class
assert_not_equal [1,2,3,4,5], (1..5)
assert_equal [1,2,3,4,5], (1..5).to_a
assert_equal [1,2,3,4], (1…5).to_a
end
[/sourcecode]

Again, identifying the class object type is easy, a range of numbers is a Range Object. Check. A range stating 1..5 does not provide the numbers one through five. Calling to_a on a range however does provide you those numbers. Doing the same thing to an array specified with three periods instead of two with the to_a provides numbers one through four. That seems odd, but I got it.

[sourcecode language=”ruby”]
def test_slicing_with_ranges
array = [:peanut, :butter, :and, :jelly]

assert_equal [:peanut, :butter, :and], array[0..2]
assert_equal [:peanut, :butter], array[0…2]
assert_equal [:and, :jelly], array[2..-1]
assert_equal [:peanut, :butter, :and], array[0..-2]
end
[/sourcecode]

Slicing an array of four values, stating the starting and ending point with the syntax of a range, provides the elements based on the values associated with that range. I actually added an assert to this test to determine what exactly the negative values do. It appears that the array starts at the point of the first number, then follows a range from that until the negative number from the end of the array. So with 10 items, starting at point 2 and ending -2 from the end will retrieve the middle 6 elements. Strange, but I can see how this would be very useful.

[sourcecode language=”ruby”]
def test_pushing_and_popping_arrays
array = [1,2]
array.push(:last)

assert_equal [1,2,:last], array

popped_value = array.pop
assert_equal :last, popped_value
assert_equal [1, 2], array
end
[/sourcecode]

Pop. Easy, get that last value. But wait a second, the array itself doesn’t have :last in it? Aha! Popping it not only gets that last value, but literally takes the value out of the array.

[sourcecode language=”ruby”]
def test_shifting_arrays
array = [1,2]
array.unshift(:first)

assert_equal [:first, 1, 2], array

shifted_value = array.shift
assert_equal :first, shifted_value
assert_equal [1,2], array
end

end
[/sourcecode]

Ah, kind of like a popped value but shifted out of the array? Weird, this is a little confusing at first. I see what it is appearing to do, but figured a good read of the documentation would be good. I did a search on Google and the first hit is someone asking this question.

What does Ruby’s Array Shift Do?

From that quick read it appears that shift and unshift are used similar to pop and push in a stack (ala git, etc).

That answers that question. With that, I’m off to other realms.

More Code Kōans

This is a continuation of my effort to get through all of the Ruby Kōans.

[sourcecode language=”ruby”]
def test_creating_arrays
empty_array = Array.new
assert_equal Array, empty_array.class
assert_equal 0, empty_array.size
end
[/sourcecode]

Creating a new array, just use Array.net. That I like. 🙂 Next assert verifies that the class is an Array. The third assert verifies that we have an empty array. That works, very logical, very array like.

[sourcecode language=”ruby”]
def test_array_literals
array = Array.new
assert_equal [], array

array[0] = 1
assert_equal [1], array

array[1] = 2
assert_equal [1, 2], array

array << 333
assert_equal [1, 2, 333] array
end
[/sourcecode]

array[0] makes sense, seems par for the course. Now << operator putting the value of 333 into the array in the next available position. I’m a fan. 😀

[sourcecode language=”ruby”]
def test_accessing_array_elements
array = [:peanut, :butter, :and, :jelly]

assert_equal :peanut, array[0]
assert_equal :peanut, array.first
assert_equal :jelly, array[3]
assert_equal :jelly, array.last
assert_equal :jelly, array[-1]
assert_equal :butter, array[-3]
end
[/sourcecode]

Ok, this is somewhat understandable. The peanut (with the colon? why is the colon included?) is the first value. Cool. That makes sense. The zero is actually the first part of the array, which matches well to array.first, still making sense. The jelly value is in the 3rd, or last location and I’m good with that. Now it gets weird, where is -1? I suppose it is jelly since that test now asserts true. Negative 3 is butter though, which I guess negative values just start from the end. Does that make sense? Either way, it appears to be working that way.

NOTE: This is a a great scenario, to me, and maybe for others, when taking notes pays off. It doesn’t matter if you’re studying for a test or not. I didn’t quit realize what was happening here until I wrote a note, simply explaining it back to myself. Even if you think you get something, writing it down and forcing yourself to think it through is a proven method to putting something to memory.

[sourcecode language=”ruby”]
def test_slicing_arrays
array = [:peanut, :butter, :and, :jelly]

assert_equal [:peanut], array[0,1]
assert_equal [:peanut, :butter], array[0,2]
assert_equal [:and, :jelly], array[2,2]
assert_equal [:and, :jelly], array[2,20]
assert_equal [], array[4,0]
assert_equal [], array[4,100]
assert_equal nil, array[5,0]
end
[/sourcecode]

Basically the array is saying, give me one item based on the index of 0. The second assert is starting at index 0 and providing the next two array elements. The same thing then happens for the next two. Of course, starting at index 2 and getting the next 20 values just gets the available values. I can cope with that. The next two asserts then return no value, as there is no 4th array position (remember, it starts at zero.) The last item asks for no items from the array, thus nil is returned.

Well, that’s it for now. More to come in the near future.

Code Kōans

Recently (albeit it seems a few years after a lot of my fellow developers) I’ve dug into kōans. A kōan (Chinese 公案, Korean 공안, I had to put the symbols, but I just find them awesome 🙂 ) is a fundamental part of the history and lore of ZenBuddhism. It consists of a storydialogue, question, or statement, the meaning of which cannot be understood by rational thinking but may be accessible through intuition. The classic example is “Two hands clap and there is a sound; what is the sound of one hand?

The first set of koans I checked out (thanks to @Ang3lfir3) were the Clojure Kōans. I’ll admit, I had a slightly higher priority with Ruby so I grabbed the Ruby Kōans. I’ll get to the Clojure ones soon, as Clojure is a great language to work through and derive meaning through intuition. With that little intro, I’ll dive in…

The first file is absurdly easy, basically making sure reality exists in that true is true and true is not false. These seem pretty straight forward. When I got into the subsequent koan test files though, things started to get interesting. The Ruby Language itself started to show itself and how it actually works. When working through the koans, you’re actually working with real Ruby Unit Tests and code files. In my descriptions below I’ve cut those files up so I can comment in between each bit of code. I will however format each bit of code properly for readability. Cheers!

[sourcecode language=”ruby”]
class AboutObjects &lt; EdgeCase::Koan
def test_everything_is_an_object
assert_equal true, 1.is_a?(Object)
assert_equal true, 1.5.is_a?(Object)
assert_equal true, "string".is_a?(Object)
assert_equal true, nil.is_a?(Object)
assert_equal true, Object.is_a?(Object)
end
[/sourcecode]

After running through this test, it’s a little obvious the point. Everything is an object. Get it? :O

[sourcecode language=”ruby”]
def test_objects_can_be_converted_to_strings
assert_equal "123", 123.to_s
assert_equal "", nil.to_s
end
[/sourcecode]

Ok, so I kind of feel that to_s is a bit silly for a method name, but whatever. I’m also assuming at this point that “nil” is a reserved object or something. I’m not sure what the assumption of nil is though, since it is an empty string, but sort of null, but not null, but maybe no value? I’ll just have to look this bit up later.

I did a search to dig this up and am even more confused now. I found this entry first, which would lead me to believe that nil is also a method on an object, but an object itself? Ok, I’ll read more later and move on to the next tests, maybe intuition will strike and I’ll all of a sudden realize what I’m working with here.

[sourcecode language=”ruby”]
def test_objects_can_be_inspected
assert_equal "123", 123.inspect
assert_equal "nil", nil.inspect
end
[/sourcecode]

The inspect method, seems simple enough. The method is or has a sort of default print out of what it is called under “inspection”. Ok, next…

[sourcecode language=”ruby”]
def test_every_object_has_an_id
obj = Object.new
assert_equal Fixnum, obj.object_id.class
end
[/sourcecode]

This is simple enough, every object gets an ID, whatever it may be. I’d bet it is unique, not that this test proves that. …I do wonder though, what exactly is Fixnum?

[sourcecode language=”ruby”]
def test_every_object_has_different_id
obj = Object.new
another_obj = Object.new
assert_equal true, obj.object_id != another_obj.object_id
end
[/sourcecode]

Ok, as I suspected, object IDs are unique. Got it.

[sourcecode language=”ruby”]
def test_some_system_objects_always_have_the_same_id
assert_equal 0, false.object_id
assert_equal 2, true.object_id
assert_equal 4, nil.object_id
end
[/sourcecode]

Umm. Yeah. Ok. That makes sense sort of. I’m now more confused about nil. It is 4, or null, or part of an enumeration? Who knows, who could tell from this test. I’ve got it though, false is zero, and two is true for some reason? I want to know what happened to one, which I suppose, is another thing I’ll have to intuit later. Onward!

[sourcecode language=”ruby”]
def test_small_integers_have_fixed_ids
assert_equal 1, 0.object_id
assert_equal 3, 1.object_id
assert_equal 5, 2.object_id
assert_equal 7, 3.object_id
assert_equal 9, 4.object_id
assert_equal 11, 5.object_id
assert_equal 13, 6.object_id
assert_equal 201, 100.object_id
# THINK ABOUT IT: 2x the number +1 == WTF? Why choose that?
# What pattern do the object IDs for small integers follow?
end
[/sourcecode]

Ok, I wanted to verify what the pattern was, so I actually added some asserts to this test. Hmmm, it appears, after adding the tests, that there is this nifty patter but I just can’t put my finger on it! 😉 (in case it isn’t evident, I’m being sarcastic here)

[sourcecode language=”ruby”]
def test_clone_creates_a_different_object
obj = Object.new
copy = obj.clone
assert_equal true, obj != copy
assert_equal true, obj.object_id != copy.object_id
end
end
[/sourcecode]

Ok, verified that object IDs stay unique upon creation or even cloning of new objects. This is an important thing to realize and understand within the overall design of Ruby. Enough for this short work through, more later, and again go and check out the Ruby Kōans yourself, they’re a lot of fun to work through.