Ruby Binary Search Issue - sorted array / x is nil error -
i know few questions similar title have been closed ambiguity, try detailed possible.
i have rails model called 'badges' have 13 badge objects predefined. each badge object has attr called 'condition', specifies number of points user must reach achieve badge.
my code method called 'reward_badge' this:
@user = user.find(self.user_id) conditions = array.new(13) badge.all.each |b| conditions << b.condition end badge = badge.find(conditions.bsearch_index{|x| @user.points >= x} + 1) @user.badges << badge unless @user.badges.include? badge so, have sorted array called 'conditions' contains point increments each of badges (ex. [1, 5, 10, 50...]). want badge has condition smaller user's points, , award badge if user doesn't have it.
and decided 'binary search' ruby provides best way achieve this. when use above code, errors saying 'x nil'. (more specifically, error says cannot use operator '>=' nil obj)
i not sure how resolve this, thought followed ruby library specifies...
at moment, decided temporarily use case statement. hope use binary search method clearer solution. appreciate help.
to fetch badge based on user points, use:
badge = badge.where('condition <= ?', @user.points).order(:condition).last
Comments
Post a Comment