Skip to content

Instantly share code, notes, and snippets.

@robinclart
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinclart/9431901 to your computer and use it in GitHub Desktop.
Save robinclart/9431901 to your computer and use it in GitHub Desktop.
Randomize the content within brackets in the form of [ a | b ]
require "benchmark"
# Originally written by @blazeeboy
# See https://gist.github.com/9429208
def generate(result)
# ...
end
def randomize_sentence(sentence)
randomized_sentence = sentence.gsub(/\[[^\[\]]+\]/) { |s| s[1..-2].split("|").shuffle.first }
randomized_sentence == sentence ? randomized_sentence : randomize_sentence(randomized_sentence)
end
sentence = "[Hello|Hi] my [friend|dear], how [are you [today|these days]|is your brother]!"
Benchmark.bm do |x|
x.report "Emad " do
10000.times { generate(sentence) }
end
x.report "Robin" do
10000.times { randomize_sentence(sentence) }
end
end
# >> user system total real
# >> Emad 0.530000 0.000000 0.530000 ( 0.532713)
# >> Robin 0.160000 0.000000 0.160000 ( 0.158647)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment