Re: LocalJumpError calculating the median

Frederick Cheung
2009-06-24T10:27:25Z

On Jun 24, 9:59 am, simon180
<oneeightystud...-gM/Ye1E23mwN+BqQ9rBEUg@public.gmane.org>
wrote:
> The example code in my view is as follows:
>
> <%= survey_response.median([6,4,5,4,4,2]) %>
> Then in survey_response.rb model the methods are as follows:
>
> def mean(array)
>   array.inject(array.inject(0) { |sum, x| sum += x } /
> array.size.to_f)
> end

You''ve got two calls to inject there, but only the inner one has a
block. Not sure what the second call to inject should be doing - i
don''t think you need it at all.

Fred
>
> def median(array,already_sorted=false)
>   return nil if array.empty?
>   array = array.sort unless already_sorted
>   m_pos = array.size / 2
>   return array.size % 2 == 1 ? array[m_pos] : mean(array
> [m_pos-1..m_pos])
> end
>