From: Robert Klemme Date: 2008-08-28T02:05:34+09:00 Subject: Re: how to avoid passing by reference and how to copy objects On 27.08.2008 09:10, Adam Akhtar wrote: > I first learnt C so used to being able to pass by reference or by value. > In Ruby its just by reference (so ive just found out after an hour of > chasing a bug). Well, it's actually an advantage because passing a reference is usually faster than passing an object by value. > I have an array of ojbects which are baisically acting like structures. > I want to pass the array to a function. This function will take the > array, make a new copy so as to protect the original from any changes. > Changes will be made to the copy and then the copy is returned. > > How do i do that? > > Ive looked dup but i dont think it works for objects... isnt there a > method to copy an object (i.e make new space in memory and put the data > there rather than juts pointing to the original objects address). > > Id have thought it was necessary if you can only pass by reference...or > is the above considered bad design practice in ruby? Adding to the excellent advice: depending on what you have in your structs you can also use Array#map to get a copy like this: def f(x) copy = x.map {|el| el.dup} end or even def f(x) x.map do |el| # your calculation on each el YourStruct.new some, more, values, like, el.length + 1 end end As I said, whether it's safe depends on your data. But I fully agree to Brian's remark that something like this (deep copy) is usually not done. It depends on your problem at hand which is the best approach so if you provide a little more detail we might be able to provide more concrete advice how to tackle your particular situation. Kind regards robert