From: Austin Ziegler Date: 2003-03-29T03:45:45+09:00 Subject: Re: Array question On Fri, 28 Mar 2003 22:48:19 +0900, walter@mwsewall.com wrote: >>> |#I want to do this >>> |puts list.join(","){|item| item.downcase} >>> | >>> |#but I have to do this >>> |puts list.collect{|item| item.downcase}.join(",") > I didn't actually want to change the array items themselves, just > use the results of the block for the join. If there was no block > it would work just as it does now joining the array element > directly. > I have only used Ruby for a couple of weeks and I have used this > type of thing at least a few times. collect then join works, I > just thought it would be faster and use less memory if join took a > block and did it directly. > It would also seem similar to me to the way that sort works. > Without a block sort uses <=> but if given a block it will use the > results of that for the sorting. I was looking for the same basic > functionality for join. Your example could be done, however, with: puts list.join(", ").downcase If you wanted to use #capitalize, though, you need to collect. I think that join could take a block, but I'd want it to be more like: list.join do |current, next| if next.nil? "" elsif (next - current) > 1 " ... " else ", " end end Thus, if my list is: list = [1, 2, 3, 5, 8, 9, 10] the result would be: 1, 2, 3 ... 5 ... 8, 9, 10 -austin (sample code follows) class Array def blockjoin val = "" each_with_index do |e, i| sep = yield e, self[i + 1] val << e.to_s << sep end val end end list = [1, 2, 3, 5, 8, 9, 10] puts list.blockjoin { |c, n| if n.nil? "" elsif (n - c) > 1 " ... " else ", " end } -- Austin Ziegler, austin@halostatue.ca on 2003.03.28 at 13:29:09