我想知道是否可以从传递给Each的块中放置的for循环中返回Ruby中的每个迭代器。
def find member = ""
productHash = {}
#@entries is a hash, with both the keys and values being strings
#the member parameter is a string
@entries.each do |key, value|
for i in 0...member.size
if(key[i] != member[i])
next #the next keyword doesn't work...all it does is return to the for iterator. I'm looking for a keyword that would return to the each iterator, and allow each to pass back in the next key-value pair.
end
end
productHash[key] = value
end
productHash
end
我想要完成的是:当我看到成员参数中的字符与给定键中的相应字符不匹配时,我转到下一个键值对。
答案 0 :(得分:1)
看起来您正在尝试进行某种比较,如果密钥与member
指定的特定前缀匹配,那么您将进行分配。
此代码应在功能上类似:
def find(member = "")
hash = { }
@entries.each do |key, value|
# Unless key begins with prefix, skip it.
next unless (key[0, prefix.length] == prefix)
hash[key] = value
end
hash
end
Ruby中没有正式的goto
声明,许多人认为这是件好事,但这意味着破坏嵌套块可能有点棘手。
但是,如果你以正确的方式解决问题,那么几乎总会有一个足够优雅的解决方案。
<强>更新强>
要打破嵌套循环,方法可能是:
list.each do |i|
broken = false
inner_list.each do |j|
if (j > 10)
broken = true
break
end
end
break if (broken)
end