Thursday, January 21, 2010

String iteration and (basic) string formatting

Some unit tests that demonstrate string iteration and rudimentary string formatting:

def testStringIteration() {
  let i = "Test".iterate();
  assertEq('T', typecast[char](i.next()));
  assertEq('e', typecast[char](i.next()));
  assertEq('s', typecast[char](i.next()));
  assertEq('t', typecast[char](i.next()));
  assertTrue(i.next() isa void);

  let i2 = "\u2100".iterate();
  assertEq(0x2100, typecast[char](i2.next()));
  assertTrue(i2.next() isa void);
}

def testStringFormat() {
  assertEq("Test {}", String.format("Test {{}}"));
  assertEq("Test Hello", String.format("Test {0}", "Hello"));
  assertEq("Test Hello", "Test {0}".format("Hello"));
}





Note that you can call 'format' either as a static method of class String, or as an instance method on a string literal.

One idea that I was considering was making strings callable. The rationale was that I wanted something really short for string formatting - like Python's original, now-deprecated '%' operator. Well, one way to do that is to simply remove the ".format" part of the expression, which gives you something like "Test {0}"("Hello"). However, I decided that this looked a little too dense in terms of punctuation - treading perilously close to the "looks like line noise" territory.

No comments:

Post a Comment