I've started with Ruby and am finding new, shorter, elegant ways to write code everyday.
In solving Project Euler problems, I've written a lot of code like
if best_score < current_score
best_score = current_score
end
Is there a more elegant way to write this?
best_score = [best_score, current_score].max
see: Enumerable.max
disclaimer: although this is a little more readable (imho), it's less performant:
require 'benchmark'
best_score, current_score, n = 1000, 2000, 100_000
Benchmark.bm do |x|
x.report { n.times do best_score = [best_score, current_score].max end }
x.report { n.times do
best_score = current_score if best_score < current_score
end }
end
will result in (with ruby 1.8.6 (2008-08-11 patchlevel 287)):
user system total real
0.160000 0.000000 0.160000 ( 0.160333)
0.030000 0.000000 0.030000 ( 0.030578)
This can be done on a single line:
best_score = current_score if best_score < current_score
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With