Ruby yield is used to control the rollback for blocking (for example, an anonymous function) to execute block statements and then return back to where the block was called.
With yield args
you can pass arguments to a block, and with lvar = yield
you can get the return and bind it to lvar after the control exits the block. This is a very general and consistent feature design in Ruby. And of course, you can apply this idea to iterate over collections.
While mostly in Python people use yield to facilitate efficient access to elements due to some collection, they focus on iteration once and generate an βon the flyβ ever-called idea, which is the main use of yield in Python.
FYI is not exactly the difference between Python and Ruby on yield , at least in the way it is used. (Apparently, they are implemented in different ways, since for python yield creates a generator that does not run any code unless the iteration begins). For example, the yield method is used in the python contextmanager, in Ruby it is exactly the same.
from contextlib import contextmanager @contextmanager def openfile(name, mode): f= open(name, mode) yield f f.close() with openfile('log.txt', 'r') as handle: for line in handle: print line
here execute pass file descriptor with and execute c-operators exactly once , and then return to the file closing statement
source share