Created
January 21, 2015 11:18
-
-
Save paractmol/27fd03dfdfb7da46fe74 to your computer and use it in GitHub Desktop.
custom_max.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def custom_max | |
idx = self[0] > self[1] ? 1 : 0 | |
self.delete_at(idx) | |
self.length <= 1 ? self[0] : self.custom_max | |
end | |
end | |
a = [4,3,6,1,44,4,8,31,41,2,1,98,2,3,1,8,32,1,4,5,6] | |
puts a.custom_max.inspect | |
puts a.inspect #original array modificated | |
###################### | |
puts "--------------- New Example ---------------" | |
class Array | |
def custom_max | |
@copy = self.dup unless defined?(@copy) | |
idx = @copy[0] > @copy[1] ? 1 : 0 | |
@copy.delete_at(idx) | |
if @copy.length <= 1 | |
max = @copy[0] | |
@copy = self.dup | |
max | |
else | |
self.custom_max | |
end | |
end | |
end | |
a = [4,3,6,1,44,4,8,31,41,2,1,98,2,3,1,8,32,1,4,5,6] | |
puts a.custom_max.inspect | |
puts a.inspect #original not modificated | |
puts a.custom_max | |
puts a.custom_max | |
puts a.custom_max | |
puts a.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment