Devin Mullins
12/31/2006 9:31:00 PM
Phrogz wrote:
> What makes the final separator so special that it deserves inclusion,
> while making no allowance for a pre-separator? Just the English
> language?
Well, just for poops and giggles, here's a less racist alternative
(JEG-compatible):
require "enumerator"
class Array
alias old_join join
def join(sep = $,, last_sep = nil, &each_prefix)
each_prefix ||= proc do |e,i|
(last_sep if i == length - 1) || sep
end
enum_with_index.map do |e,i|
i == 0 ? e : "#{each_prefix[e,i]}#{e}"
end.old_join
end
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
class TestJoin < Test::Unit::TestCase
def test_old_matches_new
assert_equal([].old_join, [].join)
assert_equal([1].old_join, [1].join)
assert_equal([1, 2].old_join, [1, 2].join)
assert_equal((1..5).to_a.old_join, (1..5).to_a.join)
assert_equal([].old_join("|"), [].join("|"))
assert_equal([1].old_join("|"), [1].join("|"))
assert_equal([1, 2].old_join("|"), [1, 2].join("|"))
assert_equal((1..5).to_a.old_join("|"), (1..5).to_a.join("|"))
end
def test_new_last_arg_behavior
assert_equal("1, 2, 3, 4, and 5", (1..5).to_a.join(", ", ", and "))
assert_equal("1, 2, 3, 4 and 5", (1..5).to_a.join(", ", " and "))
assert_equal("1, 2, 3, 4 & 5", (1..5).to_a.join(", ", " & "))
assert_equal([1, 2].join(","), [1, 2].join("ignored", ","))
end
def test_new_block_behavior
assert_equal '1 dna, 2, 3, 4, 5',
(1..5).to_a.join {|e,i| i == 1 ? ' dna, ' : ', ' }
end
end
end