在哈希迭代器中使用 proc 而不是块

using proc instead of block inside hash iterator

我为我正在处理的 class 编写了自己的迭代器,它扩展了 hash.

我编写的迭代器是使用块实现的,现在我正在尝试使用 Proc 实现同样的事情。但我有点不知道如何在这种情况下使用它! :(

def each_word
   rank=0
   self.sort_by{|k,v| v}.reverse.to_h.keys.each{ |key,abs, rel | yield rank+=1, 
   key,self[key], self.frequency(key) if block_given? }#iterate with aid block
end

我会这样使用它:

puts "Rang - Anzahl - Häufigkeit(%) - Wort"
obj1.each_word do |rank,word,abs ,rel|
  puts "#{rank}         #{abs}       #{rel}%        #{word} "
end

使用 Proc(代码不正确)

问题是我想使用 Proc

获得相同的代码
def each_letter
  rank=0
  x=self.sort_by{|k,v| v}.reverse.to_h# this wont work but wrote it as helpless try
  my_proc=Proc new { |key,abs, rel | yield rank+=1, key,x[key], x.frequency(key) }
  my_proc.call()
end

我已经看过那些页面了

那么使用提供的字母块的正确方法是什么?!

编辑作业文本:

each_word iterate over the words found using the method and a block, starting with the most common word to the least common word. The block gets the word, the absolute and relative frequency passed.(which I assume I did correctly)

The letter statics each_letter It behaves similarly to each_word, but within the method, you should use a Proc instead of a block.

你在这里所做的尝试是 wrapping yield with a Proc,但实际上你可以 replace yield with the Proc:

def each_word(&proc)
   rank=0
   keys = self.sort_by{|k,v| v}.reverse.to_h.keys
   keys.each do |key, abs, rel|
     if proc
       proc.call(rank+=1, key,self[key], self.frequency(key))
     end
   end
end

什么&proc 它采用传入的(无论是do ... end还是{ ... }语法)和转换它为一个过程。

要检查是否给出了一个块,您只需使用 if proc(而如果您使用 yield,则使用 block_given?)。您也可以使用 proc&.call,即 safe navigation operator.

顺便说一句,您可能应该将 rank +=1 更改为 rank + 1,在这里重新分配变量的值是没有意义的,因为它不会改变散列中的值(数字是不可变的) ).