Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby script to rank array items, considering same ranks.
#! /usr/local/bin/ruby
# coding: utf-8
#**********************************************************
# Ruby script to rank array items, considering same ranks.
#**********************************************************
#
class Array
def rank
# 以下の場合は例外スロー
# - 自身配列が空
# - 自身配列に数値以外の値を含む
raise "Self array is nil!" if self.size == 0
self.each do |v|
raise "Items except numerical values exist!" unless v.to_s =~ /[\d\.]+/
end
# ランク付け
self.map { |v| self.count { |a| a > v } + 1 }
end
end
a = [9, 3, 2, 7, 1, 6, 8, 5, 10, 4]
b = [6, 8, 5, 8, 4, 9, 3, 3, 7, 1]
c = [6, 8.5, 5, 3.2, 7, 1, 8.1, 3.2, 9, 3]
d = [9, 3, 2, 7, "abc", 6, 8, 5, 10, 4]
puts "a = #{a}"
puts "--> #{a.rank}"
puts
puts "b = #{b}"
puts "--> #{b.rank}"
puts
puts "c = #{c}"
puts "--> #{c.rank}"
puts
puts "d = #{d}"
puts "--> #{d.rank}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment