Skip to content

Instantly share code, notes, and snippets.

@durrellchamorro
Created November 6, 2015 17:12
Show Gist options
  • Save durrellchamorro/d037714ce6eb794d783f to your computer and use it in GitHub Desktop.
Save durrellchamorro/d037714ce6eb794d783f to your computer and use it in GitHub Desktop.
Three Approaches To Reversing A String
require 'benchmark'
class String
def swap!(a,b)
self[a], self[b] = self[b], self[a]
self
end
end
string1 = "Pneumonoultramicroscopicsilicovolcanoconiosis"
string2 = "Pneumonoultramicroscopicsilicovolcanoconiosis"
string3 = "Pneumonoultramicroscopicsilicovolcanoconiosis"
def fastest_reverse(string)
array = string.chars
new_array = []
until array.empty? do
new_array << array.pop
end
new_array.join
end
def reverse(string)
array = string.chars
new_array = []
string.size.times do
new_array << array.pop
end
new_array.join
end
def slowest_reverse!(string)
index1 = 0
index2 = -1
(string.size / 2).times do
string.swap!(index1, index2)
index1 += 1
index2 -=1
end
string
end
Benchmark.bm do |x|
x.report { fastest_reverse(string2) }
x.report { reverse(string3) }
x.report { slowest_reverse!(string1) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment