1

我想知道是否可以从放置在传递给 Each 的块中的 for 循环中返回到 Ruby 中的 Each 迭代器。

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

我想要完成的是:当我看到成员参数中的字符与给定键中的相应字符不匹配时,我将继续进行下一个键值对。

4

1 回答 1

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
于 2013-05-01T02:02:17.283 回答