Created
July 9, 2014 00:18
-
-
Save mayfer/96ba957fb8b55c2b9118 to your computer and use it in GitHub Desktop.
Three alternative methods of looping in ruby to find the maximum number in an array.
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
def maximum(numbers) | |
largest = numbers.first | |
index = 0 | |
# keep looping over every element in the array | |
while index < numbers.size | |
# check to see if current number is larger than the largest one so far | |
if numbers[index] > largest | |
# if so, assign it as the largest value | |
largest = numbers[index] | |
end | |
# move to the next element | |
index += 1 | |
end | |
return largest | |
end | |
# alternative looping for same algorithm | |
def maximum(numbers) | |
largest = numbers.first | |
# compare each number with the largest so far | |
for index in 0..(numbers.size - 1) | |
# puts "Index #{index}, value #{numbers[index]}" | |
if numbers[index] > largest | |
# puts "YES, larger" | |
largest = numbers[index] | |
end | |
end | |
return largest | |
end | |
# a more ruby-like method of looping | |
def maximum(numbers) | |
largest = numbers.first | |
# compare each number with the largest so far | |
numbers.each do |number| | |
# puts "Index #{index}, value #{numbers[index]}" | |
if number > largest | |
# puts "YES, larger" | |
largest = number | |
end | |
end | |
return largest | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment