我已经尽力了解代码的每一行是如何工作的,但看起来我只是在我走的时候迷失了。我知道http://ruby.learncodethehardway.org/book/ex39.html解释了函数,但我对实际代码感到迷茫。一个例子是k,v = kv如何用于获取槽函数。我可以详细解释一下迭代变量在这段代码中是如何工作的吗?
module Dict
def Dict.new(num_buckets=256)
# Initializes a Dict with the given number of buckets.
# As far as i can tell for this bit of code is that it creates an array called aDicts what will store 255 separate arrays
# and each time a new Dict is inialized it will create an array that holds 255 arrays
aDict = []
(0...num_buckets).each do |i|
aDict.push([])
end
return aDict
end
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
def Dict.get_bucket(aDict, key)
# Given a key, find the bucket where it would go.
#Takes the Dict.hash_key functions and stores it in bucket_id
#I am guessing this allows the assigned of hash_key to an index of aDict? Not to sure
bucket_id = Dict.hash_key(aDict, key)
return aDict[bucket_id]
end
def Dict.get_slot(aDict, key, default=nil)
# Returns the index, key, and value of a slot found in a bucket.
#Gets the bucket_id/index or index value and stores it in bucket
bucket = Dict.get_bucket(aDict, key)
#I honestly am lost how this iterator works especiallys on whats going on with the varibles
bucket.each_with_index do |kv, i|
k, v = kv
if key == k
return i, k, v
end
end
#No clue on where the -1 comes it
return -1, key, default
end
def Dict.get(aDict, key, default=nil)
# Gets the value in a bucket for the given key, or the default.
#Im lost here to
i, k, v = Dict.get_slot(aDict, key, default=default)
return v
end
def Dict.set(aDict, key, value)
# Sets the key to the value, replacing any existing value.
#little understanding of how the rest of this code works
bucket = Dict.get_bucket(aDict, key)
i, k, v = Dict.get_slot(aDict, key)
if i >= 0
bucket[i] = [key, value]
else
bucket.push([key, value])
end
end
def Dict.delete(aDict, key)
# Deletes the given key from the Dict.
bucket = Dict.get_bucket(aDict, key)
(0...bucket.length).each do |i|
k, v = bucket[i]
if key == k
bucket.delete_at(i)
break
end
end
end
def Dict.list(aDict)
# Prints out what's in the Dict.
aDict.each do |bucket|
if bucket
bucket.each {|k, v| puts k, v}
end
end
end
end
答案 0 :(得分:1)
如果你有一个数组,比如
name = ["John", "Doe"]
你可以做什么叫"多次转让"它在右边有多个元素,并将它们分配给左边的多个变量。
first_name, last_name = name
p first_name
=> "John"
p last_name
=> "Doe"
该行
k,v = kv
是那种多重赋值。 kv
包含多个值
我们可以在Dict.set方法中看到这个......
if i >= 0
bucket[i] = [key, value]
else
bucket.push([key, value])
end
很明显,每个桶条目都是一个键和值的数组。