[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Cleaner way to do this?

Harry Ohlsen

11/5/2004 12:19:00 AM

Hi,

One of my colleagues asked me last night how he could do some processing
on every object of an array, with different processing for the first
item ... but without generating an intermediate variable.

An example would be doing the equivalent of

puts a.join(", ")

without having a temporary string created. The temporary string isn't
an issue normally, but imagine if the array is huge.

Trying to make it reasonably flexible, I came up with the following, but
I figure there's probably some cleaner way to do it.

Maybe there's a method I don't know about that allows for this kind of
thing. Any suggestions?

Pardon the method name ... it's only a model :-)

class Array
def first_and_rest(first_time)
first_time.call self[0]

(1 .. self.length - 1).each do |i|
yield self[i]
end
end
end

a = [1, 2, 3, 4, 5]

File.open("test.txt", "w") do |out|
a.first_and_rest(proc {|x| out.print x}) do |x|
out.print ", #{x}"
end

out.puts
end


************************************************************************

If you have received this e-mail in error, please delete it and notify the sender as soon as possible. The contents of this e-mail may be confidential and the unauthorized use, copying, or dissemination of it and any attachments to it, is prohibited.

Internet communications are not secure and Hyperion does not, therefore, accept legal responsibility for the contents of this message nor for any damage caused by viruses. The views expressed here do not necessarily represent those of Hyperion.

For more information about Hyperion, please visit our Web site at www.hyperion.com





2 Answers

Wayne Vucenic

11/5/2004 1:12:00 AM

0

How about

[1, 2, 3, 4, 5].each_with_index do |x, i|
if i == 0
print x
else
print ", ",x
end
end

Wayne

-----
No Bugs Software
"Ruby and C++ Contract Programming in Silicon Valley"


Ara.T.Howard

11/5/2004 2:18:00 AM

0