From: "Aleksi Niemelä" Date: 2000-12-14T15:21:04+09:00 Subject: [ruby-talk:7198] Harmful preselection by yielding? Dave's answer made me wonder: > def getpwent > File.foreach("/etc/passwd") do |line| > yield line.split(/:/) > end > end > > # loop over entries in password file > > getpwent do |login, pw, uid, gid, name, home, shell| > puts "#{login} #{home}" > end If you want to let the caller use the information the routine is producing do you prefer: def foo @line.split(/:/) end or def foo yield @line.split(/:/) end I'd go for the case 1, but that was just prelude. In Dave's reply, I felt the code is simple and nice, does what it should and everybody is happy. And then suddenly I realize it leads me to more abstract thinking. Here we expand the problem to the "second order": def foo lines.collect { |line| line.split(/:/) } end foo().each {|parts| bar parts } or def foo lines.each {|line| yield line.split(/:/) } end foo {|parts| barract parts } So, do you prefer to "fix in" the yielding instead of returning the produced data structure. And which is the criteria you base your decision on (feeling goes, but something more tangible would be great)? Returning the array of arrays gives more freedom, to do whatever is needed, yielding restricts the use to be done in one way. OTOH, that one way might be very convenient, and even the only one people ever would like to use. But nevertheless, I feel this is kind of design issue for the Ruby code to be developed. I've always tried to write my code to return the whole datastructure, and that has yielded (:-) to easier reusing. However, Ruby world is might be different in this sense, so maybe I should start to look more carefully when there's really no need to return "everything" -- when the simple predetermined iteration does the trick. Maybe my fear comes from the fact I'm dismissing some potential uses prematurely. Like in this case, returning enumerable leaves the user to do whatever he wishes, but yielding "preselects" only Enumerable#each (and as a side-effect eases up this common usage). Was I confusing... - Aleksi