Daniel DeLorme wrote:
> Stefan Rusterholz wrote:
>>>
>>> Daniel
>> 
>> You are right, your solution is better.
> 
> Only partly. Unfortunately, end-anchored regular expressions have pretty
> abysmal performance.
> 
>  >> require "benchmark"
>  >> str = "?????"*1000
>  >> Benchmark.measure{10000.times{str.first}}.real
> => 0.0704410076141357
>  >> Benchmark.measure{10000.times{str.last}}.real
> => 5.35788202285767
> 
> :-(
> Daniel

That can be helped. Assuming that there is no encoding with 1 char > 8 
bytes:

def first; self[/\A./m]; end
def last; self[/.\z/m]; end
def last2; self[-8,8][/.\z/m]; end

Benchmark.measure{10000.times{str.first}}.real
=> 0.0643939971923828
Benchmark.measure{10000.times{str.last}}.real
=> 7.3151650428772
Benchmark.measure{10000.times{str.last2}}.real
=> 0.167464017868042

That's a 40x improvement for that string. For short strings it will 
probably be slightly slower, but I'd say it's worth it.

Regards
Stefan
-- 
Posted via http://www.ruby-forum.com/.