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?
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 = 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
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).
精彩评论