问题描述
作者(Russ Olsen)在 Ruby(第21页,第一版,第六次印刷) 一书中提倡使用 / code>方法,而不是 for 循环,这符合我在其他地方读过的所有内容。然而,作者还说,这样做的一个原因是循环的事实上确实调用了每个方法,那么为什么不剪掉中间人,并使用每个?所以我想知道这实际上是如何工作的。
为了调查我做了一个关于github上的Ruby repo的搜索,但是发现很难确定我能在哪里/如何
如何重新显示问题:
如何显示Ruby for循环实际上是使用每个方法实现的
#对于每个
$ b类三次元
def初始化(值)
@value =值
结束
def each( & block)
putsIn Each
block.call(@value)
block.call(@value)
block.call(@value)
结束
结束
然后创建一个实例并在for循环中使用它: p>
collection = ThreeOf.new(99)
在集合中
把i
结束
运行该命令,您将看到打印出来的信息,for循环会循环三次。 >
另外(更好玩的)你可以猴子修补内建的Array类:
class Array
alias_method:orig_each,:each
$ b $ def each(* args,&block)
putsArray Each called!
orig_each(* args,&block)
end
end
putsFor循环数组
for i in [1,2, 3]
puts i
end
再次,您将看到打印的信息。
In the book Eloquent Ruby (page 21, first edition, sixth printing), the author (Russ Olsen) advocates using the each method instead of the for loop and this is in line with everything I've read elsewhere.
However the author also goes on to say that one reason to do so is that the for loop does in fact call the each method, so why not just cut out the middle-man and use each? So I was wondering how this actually works.
To investigate I did do a search on the Ruby repo on github, but was finding it difficult to pinpoint where/how I could see this in action.
To restate the question:
How can I show the Ruby for loop is in fact implemented using the each method?
You can show it by writing a class that implements each:
# Demo that for calls each class ThreeOf def initialize(value) @value = value end def each(&block) puts "In Each" block.call(@value) block.call(@value) block.call(@value) end end
And then make an instance and use it in a for loop:
collection = ThreeOf.new(99) for i in collection puts i end
Run that and you will see the message printed out and the for "loop" will go round three times.
Alternatively (and more fun) you can monkey patch the built in Array class:
class Array alias_method :orig_each, :each def each(*args, &block) puts "Array Each called!" orig_each(*args, &block) end end puts "For loop with array" for i in [1,2,3] puts i end
And again you will see the message printed.
这篇关于我怎样才能证明Ruby`for`循环实际上是使用`each`方法实现的呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!