Skip to content

Instantly share code, notes, and snippets.

@xenjke
Created April 30, 2017 11:04
Show Gist options
  • Save xenjke/05e2303dca11674fa8320109a005ab69 to your computer and use it in GitHub Desktop.
Save xenjke/05e2303dca11674fa8320109a005ab69 to your computer and use it in GitHub Desktop.
Write a program to reverse string
require 'benchmark'
cases = [
'Word',
'Simple sentance',
'A one letter contatining sentance',
'Cover the punctuation!',
'',
'Digits h3r3 and 4there'
]
def my_reverse(string)
new_a = []
t = string.size
i = -1
t.times do |time|
new_a << string[i]
i -= 1
end
new_a.join
end
def native_reverse(string)
string.reverse
end
def test_my_realisation(cases)
cases.each do |string|
result = my_reverse(string)
test_results(string, result)
end
end
def test_built_in_realisation(cases)
cases.each do |string|
result = native_reverse(string)
test_results(string, result)
end
end
def test_results(input,output)
raise if input.reverse != output
end
n = 5000
Benchmark.bm do |x|
x.report('my:') { n.times{ test_my_realisation(cases) } }
x.report('ru:') { n.times{ test_built_in_realisation(cases) } }
end
Write a program to reverse string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment