Hacker News new | past | comments | ask | show | jobs | submit login

I believe Python has a yield statement, or am I missing something?

http://docs.python.org/whatsnew/2.5.html#pep-342-new-generat...




Indeed. Perhaps the Ruby one works different?


Yep. `yield` in Ruby is a normal anonymous method call. It pushes a new frame onto the stack. `yield` in Python works more like Ruby's [Generator](http://ruby-doc.org/stdlib/libdoc/generator/rdoc/classes/Gen...). It freezes the current stack frame's state and resumes execution somewhere else, returning again to the same place on the next iteration. They're very different things really.

More about Python's generators here:

http://www.python.org/dev/peps/pep-0255/


So what would yield in Ruby be like in Python? Surely there must be some analogue?


You can pass an anonymous function or lambda:

    def foo(thing, block):
      thing = "cruel " + thing
      block(thing) # like `yield thing' or 'block.call' in ruby

    def bar(thing):
      return "hello " + thing

    foo('world', bar)

    # or:
    foo('world', lambda x: "hello " + x)
Ruby's blocks are really just sugar for passing an anonymous function in the last argument and yield is just sugar for calling that function. The example above in Ruby would be:

    def foo(thing)
      yield thing
    end

    foo('world') { |thing| "hello " + thing }


Ruby's yield is essentially just calling an anonymous function given to it in the form of a block. e.g., the following code snippets are equivalent

Ruby:

    def foo(bar)
      if block_given?
         yield bar
      end
    end

    foo 5 { |x| puts x } # prints 5
Python:

    def foo(bar,fcn):
        fcn(bar)


    foo(5, lambda x: sys.stdout.write("%d\n" % x))
The only real difference being that the ruby code is calling a block versus a "real" function.

edit Oops, had this page open for a while, didn't realize someone had replied in the interim, making my response somewhat redundant




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: