-
-
Save mattdvhope/6043860 to your computer and use it in GitHub Desktop.
Median of an array of numbers | |
def median(array) | |
if array.length.even? | |
return (array[((array.length / 2) - 1)].to_f + array[array.length / 2].to_f) / 2 | |
else | |
return array[array.length / 2] | |
end | |
end | |
array1 = [1, 2, 3, 4, 5, 5, 7] | |
puts array1.inspect | |
puts "Median is " + median(array1).to_s | |
array2 = [4, 4, 5, 5, 6, 6, 6, 7] | |
puts array2.inspect | |
puts "Median is " + median(array2).to_s |
|Element| is a single element of the array, if the array is made of numbers then each element will be a number, if it's a mixed array and the current Element is a string then it'll pass a string to the code block, of course you will get an error if you try to .to_f to a string.
In this case though you don't really need to iterate through the array, you are doing all this work to find the position of the ones that you want and you just need to return that 'median_value'. You are iterating through median value which is returning a 'median_value' calculation for each iteration. You just want one value based on the array.length.even? condition. Just return that. I hope that helped.
Your .each method will return an array when it is done iterating over all the elements.
Thanks so much for getting me back on track--out of the weeds!!
I'm confused about what " | element | " is able/allowed to do within the code block. I had tried to return "median_value" after the second "end," but no success.