3

我的应用程序的用户有他们的观点。我想根据他们的分数为他们分配不同的等级。这是我的排名映射哈希:

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

我需要检查用户的点是否在哈希的范围键中,并提取必要的值。有什么优雅的解决方案吗?我可以使用“case”运算符,但这不会像我想要的那样优雅。

4

1 回答 1

3

您可以迭代所有键/​​值对并检查。

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

更新:

我不知道你为什么认为case它不优雅。我认为它非常优雅。

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
于 2013-04-05T09:45:48.533 回答