From: Stefano Crocco Date: 2009-01-29T05:21:34+09:00 Subject: Re: yield vs. return Alle mercoledì 28 gennaio 2009, klochner ha scritto: > I couldn't find any meaty discussions on this topic, so maybe it's > worth a post. > > Does it make sense to use yield at the end of a function, where you're > essentially > using yield to replace a return value? For example: > > def returnfoo > return foo > end > > vs. > > def yieldfoo > yield foo > end > > I see a lot of ruby programmers doing the latter, but consider the > former to > be more straightforward. There are a lot of cases where yielding is > more elegant > than return, but I don't consider this to be one of them. Anyone care > to weigh in? yield and return do completely different things, and you can't use one in place of the other. return tells ruby to stop executing the method and return its argument to the caller. yield tells ruby to call the block passed to the method, giving it its argument. yield will produce an error if the method wasn't called with a block: def test_yield yield 43 end test_yield # notice that no block was passed to the method => LocalJumpError: no block given In ruby, there's no need to put a return at the end of a method, as the method will always return the value of the last expression. This means that a method defined this way: def test_return return 4 end will give exactly the same result as a method defined this way: def test_no_return 4 end Can you give an example of a situation where you think yield is used in place of return? This way, we'll be able to understand better what you're referring to and make more useful comments. Stefano