From: Kevin Ballard Date: 2005-10-19T22:41:58+09:00 Subject: Re: Unit testing an each function ES wrote: > Whoops, sent too soon! I was going to continue >to say that while this is > nice, for clarity of expression you might want to >state it this way: > > %w{a long list of words}.collect :length But then that interferes with the ability to do [(1..5), (10..15)].each.each { |i| puts i } (which was the original point of this exercise) or any other nested enumerations such as [(1..5), (10..15)].collect.collect {|i| i + 1} Brian Schr�der wrote: > I'd understand this > > %w{a long list of words}.collect.length > as giving me the length of the return value of collect. Collect > returns an array so I'd expect the above to return five. Maybe it > would be better to write > > %w{a long list of words}.collect_with :length > > where in method missing something like this would happen > > [...] Again, same problem, plus the fact that I don't want to be using method_missing as it would interfere with any existing method_missing on the class. Pit Capitain wrote: > With the famous > > class Symbol > def to_proc > lambda { |obj| obj.send self } > end > end > > you can get the same result via > > %w{a long list of words}.map(&:length).map(&:to_s) > > I'd bet the Symbol#to_proc is somewhere in Nano. I find that much harder to read, and it also precludes the possibility of something like (1..100).reject.even? This, of course, relies on a definition of Integer#even? and having the reject method wrapped, but that's pretty easy: class Integer def even? (self % 2).zero? end end Enumerable::wrap_meth Enumerable, :reject Granted, for a single use, you'd probably just want to do (1..100).reject { |i| (i % 2).zero? } rather than defining a new method, but this example is just for illustration. Of course, it's really intended for dealing with nested enumerables, like the [(1..5), (10..15)] example above, but it does simplify very simple single-enumerable handling.