Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More elegant way to do this in Ruby

Tags:

syntax

ruby

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?

like image 736
Anurag Avatar asked Dec 21 '09 12:12

Anurag


2 Answers

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)
like image 181
miku Avatar answered Nov 01 '22 22:11

miku


This can be done on a single line:

best_score = current_score if best_score < current_score
like image 28
Trevor Avatar answered Nov 01 '22 23:11

Trevor