Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save suryart/6809931 to your computer and use it in GitHub Desktop.
Save suryart/6809931 to your computer and use it in GitHub Desktop.
How to go about removing the last element? For example, I have strings like these: str1 = "My testing String" str2 = "My another testing string" I need a neat way of showing the output: str1 = "My testing" str2 = "My another testing" This is what I could do: str1 = str1.split(" ") str1.delete(str1.last) str1.join(" ") # => "My testing" I was won…
#!/usr/bin/ruby
require 'benchmark'
str2 = "My another testing well string"
n = 500
Benchmark.bm(40) do |x|
x.report("str2[/(.*)\s/,1] "){ n.times { str2[/(.*)\s/,1] } }
x.report("str2[0...str2.rindex(' ')] "){ n.times { str2[0...str2.rindex(' ')] } }
x.report("str2.split(' ')[0...-1].join(' ') "){ n.times { str2.split(' ')[0...-1].join(' ') } }
x.report("str2[/.*(?=\s)/] "){ n.times { str2[/.*(?=\s)/] } }
end
user system total real
str2[/(.*) /,1] 0.000000 0.000000 0.000000 ( 0.001481)
str2[0...str2.rindex(' ')] 0.010000 0.000000 0.010000 ( 0.000993)
str2.split(' ')[0...-1].join(' ') 0.000000 0.000000 0.000000 ( 0.002894)
str2[/.*(?= )/] 0.000000 0.000000 0.000000 ( 0.001523)
Benchmark.bmbm(40) do |x|
x.report("str2[/(.*)\s/,1] "){ n.times { str2[/(.*)\s/,1] } }
x.report("str2[0...str2.rindex(' ')] "){ n.times { str2[0...str2.rindex(' ')] } }
x.report("str2.split(' ')[0...-1].join(' ') "){ n.times { str2.split(' ')[0...-1].join(' ') } }
x.report("str2[/.*(?=\s)/] "){ n.times { str2[/.*(?=\s)/] } }
end
Rehearsal ----------------------------------------------------------------------------
str2[/(.*) /,1] 0.000000 0.000000 0.000000 ( 0.001482)
str2[0...str2.rindex(' ')] 0.000000 0.000000 0.000000 ( 0.000918)
str2.split(' ')[0...-1].join(' ') 0.010000 0.000000 0.010000 ( 0.002903)
str2[/.*(?= )/] 0.000000 0.000000 0.000000 ( 0.001482)
------------------------------------------------------------------- total: 0.010000sec
user system total real
str2[/(.*) /,1] 0.000000 0.000000 0.000000 ( 0.000520)
str2[0...str2.rindex(' ')] 0.000000 0.000000 0.000000 ( 0.000399)
str2.split(' ')[0...-1].join(' ') 0.000000 0.000000 0.000000 ( 0.001108)
str2[/.*(?= )/] 0.000000 0.000000 0.000000 ( 0.000511)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment