doctororange
doctororange

Reputation: 11810

Elegant ruby syntax to return the greater of two objects

Of course there are a thousand ways to get this done, but is the simplest (or most elegant) way to achieve this?

[4,8].max

That's actually not too shabby, but what would you do?

Upvotes: 31

Views: 18191

Answers (3)

user48918
user48918

Reputation: 561

Okay, I tested this out of curiosity:

#!/usr/bin/env ruby
# -*- mode: ruby -*-

limit = 3000000

tstart_1 = Time.now()
(0..limit).each do |i; a,b, max|
  a = rand(9999999)
  b = rand(9999999)
  max = [a,b].max
end
puts "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 : b
end

puts "Ternary method: #{Time.now() - tstart_2} seconds"

Output:

Array method: 1.746134 seconds

Ternary method: 1.002226 seconds

Upvotes: 16

FMc
FMc

Reputation: 42421

If you don't want to spawn an array, there's the conditional operator:

max = a > b ? a : b

Upvotes: 38

Tate Johnson
Tate Johnson

Reputation: 3950

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).

Upvotes: 10

Related Questions