J
James Edward Gray II
I've been looking at the to_sentence() method in Rails. It's
basically a join(), but you can give a different final separator. I
personally use this kind of functionality often enough to believe it
would make a good addition to the core language.
Even better, I think we can make join() smart enough to eliminate any
need for to_sentence() by adding a second argument. Here's a sample
implementation:
#!/usr/bin/env ruby -w
require "enumerator"
class Array
alias_method ld_join, :join
def join(sep = $,, last_sep = sep)
return "" if empty?
enum_with_index.inject("") do |str, (e, i)|
"#{str}#{i == size - 1 ? last_sep : sep}#{e}"
end[sep.to_s.length..-1]
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
end
end
__END__
Does anyone else like this?
James Edward Gray II
basically a join(), but you can give a different final separator. I
personally use this kind of functionality often enough to believe it
would make a good addition to the core language.
Even better, I think we can make join() smart enough to eliminate any
need for to_sentence() by adding a second argument. Here's a sample
implementation:
#!/usr/bin/env ruby -w
require "enumerator"
class Array
alias_method ld_join, :join
def join(sep = $,, last_sep = sep)
return "" if empty?
enum_with_index.inject("") do |str, (e, i)|
"#{str}#{i == size - 1 ? last_sep : sep}#{e}"
end[sep.to_s.length..-1]
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
end
end
__END__
Does anyone else like this?
James Edward Gray II