I've the next code which computes the median of several amounts attracted from the database. The question pertains to if there's an simpler method for calculating the median of the column from the variety of DBI::ROWs?

Being an aside array.sort within the median calculation throws and error 'undefined method'

require 'dbi'

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

def mean(array)
    array.inject(array.inject(0) { |sum, x| sum += x } / array.size.to_f)
end

begin
    dbh = DBI.connect('DBI:jdbc:Cache://10.150.98.11:1972/SQLHRT', 'tpathhrt', 'tpathhrt',
                 'driver'=>'com.intersys.jdbc.CacheDriver')

    sth = dbh.prepare("SELECT
        DATEDIFF('hh',Result_Set.Date_Time_Booked_In,current_timestamp) AS HrsIn
            FROM
        iLabTP.Outstanding_Work_Index,
        iLabTP.Result_Set Result_Set,
        iLabTP.Request
            WHERE
        Outstanding_Work_Index.Request_Row_ID = Result_Set.Request_Row_ID and
        Outstanding_Work_Index.Request_Row_ID = Request.Request_Row_ID and
        Result_Set.Set_Code = 'TVITDN' order by HrsIn ASC")

    sth.execute()

    arr =[1]
    sth.fetch do |row|
        arr << row[0]
    end

    printf "Number of Records %d:\n", arr.size
    printf "Median %s:\n", median(arr)

    sth.finish

rescue DBI::DatabaseError => e
     puts "An error occurred"
     puts "Error code:    #{e.err}"
     puts "Error message: #{e.errstr}"
ensure
     # disconnect from server
     dbh.disconnect if dbh
end

Intersystems Caché includes a MEDIAN function:

MEDIAN

Among the good examples on that page:

SELECT MEDIAN(birthd.decade.MEMBERS, MEASURES.[%COUNT]) ON 0 FROM patients

Update

Error in array was because of nil elements in ActiveRecord set, fixed by

   <%if !statistic.HrsIn.nil? %>
   ['<%= statistic.Specimen_Number %>', <%= statistic.HrsIn %>],
   <% end %> 

Median function only in intersystems cache deep see and never regular SQL