Created
August 23, 2011 14:30
-
-
Save brandonaaron/1165279 to your computer and use it in GitHub Desktop.
A recursive partition method for Ruby's String.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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