yield
in Ruby and yield
in Python are two very different things.
In Ruby yield
runs a block passed as a parameter to the function.
Ruby:
def three
yield
yield
yield
end
three { puts 'hello '} # runs block (prints "hello") three times
In Python yield
throws a value from a generator (which is a function that uses yield
) and stops execution of the function. So it's something completely different, more likely you want to pass a function as a parameter to the function in Python.
Python:
def three(func):
func()
func()
func()
three(lambda: print('hello')) # runs function (prints "hello") three times
Python Generators
The code below (code you've provided) is a generator which returns None
three times:
def three():
yield
yield
yield
g = three() #=> <generator object three at 0x7fa3e31cb0a0>
next(g) #=> None
next(g) #=> None
next(g) #=> None
next(g) #=> StopIteration
The only way that I can imagine how it could be used for printing "Hello" three times -- using it as an iterator:
for _ in three():
print('Hello')
Ruby Analogy
You can do a similar thing in Ruby using Enumerator.new
:
def three
Enumerator.new do |e|
e.yield # or e << nil
e.yield # or e << nil
e.yield # or e << nil
end
end
g = three
g.next #=> nil
g.next #=> nil
g.next #=> nil
g.next #=> StopIteration
three.each do
puts 'Hello'
end