Skip to content

Instantly share code, notes, and snippets.

@brandonaaron
Created August 23, 2011 14:30
Show Gist options
  • Save brandonaaron/1165279 to your computer and use it in GitHub Desktop.
Save brandonaaron/1165279 to your computer and use it in GitHub Desktop.
A recursive partition method for Ruby's String.
class String
def recursive_partition(sep)
result = self.partition(sep)
if sep != "" && result[2].match(sep)
extra = result.pop
result << extra.recursive_partition(sep)
end
result.flatten
end
end
require 'test/unit'
require './recursive_partition.rb'
class RecursivePartitionTest < Test::Unit::TestCase
TEST_STR = "status=active,status=pending;start_date>=2011-01-01;end_date<2011-02-01"
def test_no_match_with_regex
result = TEST_STR.recursive_partition(/<=/)
assert_equal(result, [TEST_STR, "", ""])
end
def test_no_match_with_string
result = TEST_STR.recursive_partition("<=")
assert_equal(result, [TEST_STR, "", ""])
end
def test_single_match_with_regex
result = TEST_STR.recursive_partition(/>=/)
assert_equal(result, ["status=active,status=pending;start_date", ">=", "2011-01-01;end_date<2011-02-01"])
end
def test_single_match_with_string
result = TEST_STR.recursive_partition(">=")
assert_equal(result, ["status=active,status=pending;start_date", ">=", "2011-01-01;end_date<2011-02-01"])
end
def test_two_matches_with_regex
result = TEST_STR.recursive_partition(/;/)
assert_equal(result, ["status=active,status=pending", ";", "start_date>=2011-01-01", ";", "end_date<2011-02-01"])
end
def test_two_matches_with_string
result = TEST_STR.recursive_partition(";")
assert_equal(result, ["status=active,status=pending", ";", "start_date>=2011-01-01", ";", "end_date<2011-02-01"])
end
def test_multiple_matches_with_regex
result = TEST_STR.recursive_partition(/\=/)
assert_equal(result, ["status", "=", "active,status", "=", "pending;start_date>", "=", "2011-01-01;end_date<2011-02-01"])
end
def test_multiple_matches_with_string
result = TEST_STR.recursive_partition("=")
assert_equal(result, ["status", "=", "active,status", "=", "pending;start_date>", "=", "2011-01-01;end_date<2011-02-01"])
end
def test_with_blank_separator
result = TEST_STR.recursive_partition("")
assert_equal(result, ["", "", TEST_STR])
end
def test_with_blank_string
result = "".recursive_partition("")
assert_equal(result, ["", "", ""])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment