Ivan Danci
Ivan Danci

Reputation: 521

Conditional value extraction from ruby hash

The users of my app have their points. I want to assign them different ranks based on their points. This is my rank mapping hash:

RANKS = { (1..20)     => 'Private'
          (21..40)    => 'Corporal'
          (41..60)    => 'Sergeant'
          (61..80)    => 'Lieutenant'
          (81..100)   => 'Captain'
          (101..150)  => 'Major'
          (151..200)  => 'Colonel'
          201         => 'General'
        }

I need to check if the users' points are in a range key of the hash, and extract the necessary value. Is there any elegant solution for this? I could use 'case' operator, but that wouldn't be as elegant as I want.

Upvotes: 3

Views: 105

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

You can just iterate all key/value pairs and check.

RANKS = { (1..20)     => 'Private',
          (21..40)    => 'Corporal',
          (41..60)    => 'Sergeant',
          (61..80)    => 'Lieutenant',
          (81..100)   => 'Captain',
          (101..150)  => 'Major',
          (151..200)  => 'Colonel',
          (201..+1.0/0.0)         => 'General', # from 201 to infinity
        }


def get_rank score
  RANKS.each do |k, v|
    return v if k.include?(score)
  end

  nil
end

get_rank 1 # => "Private"
get_rank 50 # => "Sergeant"
get_rank 500 # => "General"
get_rank -1 # => nil

Update:

I don't know why you think case isn't elegant. I think it's pretty elegant.

def get_rank score
  case score
  when (1..10) then 'Private'
  when (21..40) then 'Corporal'
  when (41..1.0/0.0) then 'Sergeant or higher'
  else nil
  end
end

get_rank 1 # => "Private"
get_rank 50 # => "Sergeant or higher"
get_rank 500 # => "Sergeant or higher"
get_rank -1 # => nil

Upvotes: 3

Related Questions