我有这段代码片段,在这种情况下,一个桶只是一个更大阵列中的数组:
def Dict.get_slot(aDict, key, default=nil)
# Returns the index, key, and value of a slot found in a bucket.
bucket = Dict.get_bucket(aDict, key)
bucket.each_with_index do |kv, i|
k, v = kv
if key == k
return i, k, v
end
end
return -1, key, default
end
将名为k和v的两个变量设置为kv的竞争对象。但是,当kv一次只包含一个值时,它如何工作?
我将此写入另一个文件:
bucket = ['key', 'value']
key = 'key'
bucket.each_with_index do |kv, i|
k, v = kv
if key == k
puts k, v, i
end
end
然后v变量为空:
key
0
我的问题是,为什么多个作业在第一个例子中起作用,而在第二个例子中不起作用?
答案 0 :(得分:4)
bucket
是dictionary,只需输入:对值的列表,而不仅仅是值列表。考虑:
bucket.each do |kv|
# kv is an array: [some_k, some_v]
k, v = kv
# k is some_k
# v is some_v
end
bucket.each_with_index do |kv, i|
# kv is again an array: [some_k, some_v]
k, v = kv
# k is some_k
# v is some_v
end
作为旁注,这种"模式匹配"也可以直接用于块参数的嵌套形式:
bucket.each_with_index do |(k, v), i|
# k is some_k
# v is some_v
end
答案 1 :(得分:1)
当您致电bucket.each_with_index
时,它首先对'key'进行操作,然后是'value'
您可以尝试嵌套数组,因此在此示例中,数组的每个成员都是一个包含两个项目的数组。
irb(main):012:0> [['a','b'],['c','d']].each_with_index{|x,i|puts "#{i}: #{x}"}
0: ["a", "b"]
1: ["c", "d"]
然后,您可以通过索引
识别这些内容irb(main):019:0> [['a','b'],['c','d']].each_with_index{|x,i|puts "#{i}: #{x[0]} - #{x[1]}"}
0: a - b
1: c - d
或者使用您使用的语法将它们设置为值:
irb(main):020:0> [['a','b'],['c','d']].each_with_index{|x,i| a,b = x ; puts "#{i}: #{a} - #{b}"}
0: a - b
1: c - d
没有一个衬垫:
bucket = [
['a','b'],
['c','d']
]
bucket.each_with_index do |x, index|
k, v = x
puts index
puts "#{k} = #{v}"
end