Ruby艰难的方式ex39 .hash函数与%运算符

时间:2015-07-10 17:51:25

标签: ruby

我是Ruby新手并使用Learn Ruby the Hard Way在线书籍学习它。我在Ex39中不是很清楚:http://learnrubythehardway.org/book/ex39.html

混淆代码:

def Dict.hash_key(aDict, key)
# Given a key this will create a number and then convert it to
# an index for the aDict's buckets.

#takes the key arguments and converts it into a hash number 
# that is divided by the length
#of the Dict. The remainder a number on the aDict.
return key.hash % aDict.length
end

什么是%运算符用于。如果key.has创建了一个唯一的数字,为什么我们需要将它除以Dict的长度?

1 个答案:

答案 0 :(得分:2)

%运算符是模运算符。 (与大多数其他当前语言一样) 有了它,你可以确保最终的数字永远不会大于你所分割的数值。