Skip to content

Instantly share code, notes, and snippets.

@seiji
Created May 14, 2012 06:34
Show Gist options
  • Select an option

  • Save seiji/2692190 to your computer and use it in GitHub Desktop.

Select an option

Save seiji/2692190 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'redis'
class UserNotFoundException < Exception; end
class UserRanking
KEY="ranking"
def initialize(user_id)
@redis= Redis.new
@user_id= user_id
@myscore= (@redis.zscore KEY, user_id).to_i
if @myscore > 0
@myindex= @redis.zrevrank KEY, user_id
@myrank= get_rank(@myscore)
puts <<"EOS"
UserID: #{@user_id}
Score : #{@myscore}
Rank : #{@myrank}
EOS
else
raise UserNotFoundException, "User not found"
end
end
def get_rank(score)
score= score.to_i
(@redis.zcount KEY, score+1, Float::INFINITY) + 1
end
def display(ranking, scores={})
if ranking
ranking.each_slice(2).with_index do |(uid, score), i|
rank= scores[score] || 0
if rank < 1
rank= get_rank(score)
scores[score]= rank
end
str= "%7d %11s: %3d" % [rank, uid, score]
str << " <--- " if uid == @user_id
puts str
end
end
end
def top10()
puts "[Top10]"
ranking= @redis.zrevrange( KEY, 0, 9, {withscores: true})
display ranking, {ranking[1] => 1}
end
def near10()
puts "[Near10]"
scores= {@myscore => @myrank}
range= 5
first= (@myindex - range > 0) ? @myindex-range : 0
ranking= @redis.zrevrange(KEY, first, @myindex + range, {withscores: true})
display ranking, scores
end
end
if $0 == __FILE__
# write this
user_id= ARGV[0] || "User0234567"
ranking = UserRanking.new(user_id)
ranking.top10()
ranking.near10()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment