Array question

#I want to do this
puts list.join(“,”){|item| item.downcase}

#but I have to do this
puts list.collect{|item| item.downcase}.join(“,”)

Hmm, I feel like this filtering is not part of “join” operation.
But I’m interested in how others think.

  					matz.

Uh, no it doesn’t strike me as what ‘join’ is supposed to do.
Intuitively, I think that a ‘join’ function should only join the
entries
of the array and not modify the entries themselves.

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.

Thanks,

Walt

···

Walter Szewelanczyk
IS Director
M.W. Sewall & CO. email : walter@mwsewall.com
259 Front St. Phone : (207) 442-7994 x 128
Bath, ME 04530 Fax : (207) 443-6284


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

···

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.