def each
while input = gets
yield input.chomp
end
end
Equivilent code, actually. It’s a case of “you say tomaTOE I say
tomAHto”
Personally, I tend to prefer the ‘block.call’ because you explicitly
say you’re passing in a block in the definition of the method, so if
someone is reading your code they can easily tell that the method
takes a block. In the case of yield you might need to read through a
good bit of code before you find out that the method takes a block.
someone is reading your code they can easily tell that the method
takes a block. In the case of yield you might need to read through a
good bit of code before you find out that the method takes a block.
Phil
block.call is significantly slower since conversion from block to Proc
object involves copying references of a closure to Proc instance.
def each
while input = gets
yield input.chomp
end
end
Equivilent code, actually. It’s a case of “you say tomaTOE I say tomAHto”
Actually, the yield' version is significantly faster. When using the&block’ syntax, a Proc object is created for each iteration. From what
I’ve gathered, that doesn’t happen when using `yield’.
say you’re passing in a block in the definition of the method, so if
someone is reading your code they can easily tell that the method
takes a block. In the case of yield you might need to read through a
good bit of code before you find out that the method takes a block.
It does seem that yielding is faster; note the effect of turning the
block into a Proc object:
require ‘benchmark’
include Benchmark
n = 100000
def y
end
def b(&block)
end
bm do |x|
x.report(“call”) { n.times { b { } } }
x.report(“yield”) { n.times { y { } } }
end
That is a fairly significant difference, so maybe I should revise my
statement to say that the two different ways acheive the same effect
ignoring differences in runtime
I didn’t know that it would be faster; I only knew that using &block
is SO MUCH UGLIER!
That, my friend, is a matter of taste.
There is nothing without a purpose. Consider an object method that takes
a block and it doesn’t want to execute it immediately. What would you do
without a &block ?
without a &block ?
Utterly illogical. That is like saying that sometimes we must amputate
a
man’s foot in order to save his life, and that therefore we must always
amputate a man’s foot.
Utterly illogical. That is like saying that sometimes we must amputate
a
man’s foot in order to save his life, and that therefore we must always
amputate a man’s foot.
I think he was trying to say that there are times when yield' is the best choice, and there are times when&block’ is. It all depends on the
situation.