On Dec 31, 2006, at 12:05 PM, James Edward Gray II wrote:

> 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 :old_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

problems:

1) calculating a static value inside a loop. (only costs about a  
hundredth of a second for 10k)
2) iterating when 1/2 of your values are completely static.
3) being clever by using enumerator.

class Array
   alias_method :old_join, :join
   def join(sep = $,, last_sep = sep)
     return "" if empty?

     seperators = Array.new(size-1, sep)
     seperators[-1] = last_sep unless seperators.empty?
     self.zip(seperators).old_join
   end
end

# of iterations = 1000000
                           user     system      total        real
null_time             0.140000   0.000000   0.140000 (  0.140482)
jeg                  29.690000   0.080000  29.770000 ( 30.144816)
ryan                 19.780000   0.050000  19.830000 ( 19.998077)