Elegant ruby syntax to return the greater of two objects
If you don't want to spawn an array, there's the conditional operator:
max = a > b ? a : b
Okay, I tested this out of curiosity:
#!/usr/bin/env ruby# -*- mode: ruby -*-limit = 3000000tstart_1 = Time.now()(0..limit).each do |i; a,b, max| a = rand(9999999) b = rand(9999999) max = [a,b].maxendputs "Array method: #{Time.now() - tstart_1} seconds"tstart_2 = Time.now()(0..limit).each do |i; a,b, max| a = rand(9999999) b = rand(9999999) max = (a > b) ? a : bendputs "Ternary method: #{Time.now() - tstart_2} seconds"
Output:
Array method: 1.746134 seconds
Ternary method: 1.002226 seconds
That's exactly why Enumerable#max
has been defined for any class which implements Comparable
. It's definitely the simplest. To really understad what's happening, you'd need to look how it's been implemented in the core library of your favourite Ruby implementation (and it's probably optimised).