# LocalJumpError calculating the median

**URL:** <https://www.ruby-forum.com/t/localjumperror-calculating-the-median/170951>\
**Category:** Rails\
**Created:** [June 24, 2009, 12:18pm UTC](https://www.ruby-forum.com/t/localjumperror-calculating-the-median/170951 "2009-06-24T12:18:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![simon180](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecc23a/32.png) [@simon180](https://www.ruby-forum.com/u/simon180)\
**Post date:** [June 24, 2009, 12:18pm UTC](https://www.ruby-forum.com/t/localjumperror-calculating-the-median/170951/1 "2009-06-24T12:18:02Z")

</div>

Hi

I have searched/Googled around but I’m struggling with the following  
problem.

I am building a Rails 2.3.2 application and one of the requirements is  
to calculate the median of an array of results. I am using code for  
calculating the median from the Ruby Cookbook but keep running in to a  
problem with receiving an error ‘LocalJumpError - no block given’ when  
I attempt to find the median of an array where there are an odd number  
of members.

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

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

The error is caused when the median method refers back to the mean  
method to get the media of an odd total of items in the array. I just  
can’t figure out why I get that error or indeed how to fix it - so I’d  
hugely appreciate any help/guidance/laughing anybody could offer me!

Thanks

Simon

---

<div class="post-metadata">

**Author:** ![simon180](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecc23a/32.png) [@simon180](https://www.ruby-forum.com/u/simon180)\
**Post date:** [June 24, 2009, 12:29pm UTC](https://www.ruby-forum.com/t/localjumperror-calculating-the-median/170951/2 "2009-06-24T12:29:11Z")

</div>

On Jun 24, 9:59 am, simon180 [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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
