From: James Edward Gray II Date: 2007-04-09T21:03:57+09:00 Subject: Re: Substring like in PHP's substr()? On Apr 9, 2007, at 6:52 AM, Joshua Muheim wrote: > Hi all > > I'm looking for the coolest way to get the substring > > /Webwork/pgbookings > > out of > > /Users/Josh/Webwork/pgbookings > > The part /Users/Josh is saved in the variable my_var. > > In PHP I would do something like the following: > > substr(/Users/Josh/Webwork/pgbookings, strlen(my_var)) # => > /Webwork/pgbookings > > What's the fastest way to do this in Ruby? :-) I'm not sure which way is faster, so let's ask Ruby to time some of my ideas: #!/usr/bin/env ruby -w require "benchmark" data = "/Users/Josh/Webwork/pgbookings" prefix = "/Webwork/pgbookings" TESTS = 1_000_000 Benchmark.bmbm do |results| results.report("[i..-i]:") { TESTS.times { data [prefix.length..-1] } } results.report("[i, l]:") { TESTS.times { data[prefix.length, data.length] } } results.report("sub():") { TESTS.times { data.sub(/\A#{prefix}/, "") } } results.report("[re, c]:") { TESTS.times { data[/\A#{prefix}(.+)/, 1] } } end # >> Rehearsal -------------------------------------------- # >> [i..-i]: 2.500000 0.000000 2.500000 ( 2.511868) # >> [i, l]: 0.630000 0.000000 0.630000 ( 0.634460) # >> sub(): 6.800000 0.020000 6.820000 ( 6.850561) # >> [re, c]: 7.180000 0.010000 7.190000 ( 7.204910) # >> ---------------------------------- total: 17.140000sec # >> # >> user system total real # >> [i..-i]: 2.500000 0.000000 2.500000 ( 2.500795) # >> [i, l]: 0.630000 0.010000 0.640000 ( 0.633458) # >> sub(): 6.840000 0.000000 6.840000 ( 6.853133) # >> [re, c]: 7.110000 0.010000 7.120000 ( 7.130398) __END__ Hope that helps. James Edward Gray II