views:

523

answers:

1

I am having this problem which I can't seem to get my head around. I would like some help on this.

 @user.update_languages(params[:language][:language1], params[:language][:language2],      params[:language][:language3])
   lang_errors = @user.errors
   logger.debug "--------------------LANG_ERRORS----------101-------------" + lang_errors.full_messages.inspect
  if params[:user]
    @user.state = params[:user][:state]
    success = success & @user.save
  end
  logger.debug "--------------------LANG_ERRORS-------------102----------" + lang_errors.full_messages.inspect
  if lang_errors.full_messages.empty?

@user object adds errors to the lang_errors variable in the update_lanugages method. when I perform a save on the @user object i lose the errors that were initially stored in the lang_errors variable.

Though what i am attempting to do would be more of a hack (which does not seem to be working). I would like to understand why the variable values are washed out. I understand pass by reference so I would like to know how the value can be held in that variable without being washed out.

+9  A: 

Ruby doesn't have any concept of passing a value around. Variables are always references to objects. In order to get a object that won't change out from under you, you need to dup or clone the object you're passed, thus giving an object that nobody else has a reference to. (Even this isn't bulletproof, though — both of the standard cloning methods do a shallow copy, so the instance variables of the clone still point to the same objects that the originals did. If the objects referenced by the ivars mutate, that will still show up in the copy, since it's referencing the same objects.)

Chuck
Thank you. I'm still not sure if this is completely a good feature. Wouldn't an explicit method to pass by value be helpful though everything is an object. Another thing is I find that the cloned copy has a different object_id so doesn't that make it completely indifferent to the original object though it may hold the values of the original object or are my fundamentals totally flawed here?
Sid
Yes, the clone is a completely independent object. As for pass-by-value, it's not really compatible with pure OO, where "values" don't exist except as object state. The closest you could get is something like Objective-C's `bycopy` type modifier that tells the runtime to make a copy behind the scenes. That does sound useful.
Chuck
Thanks chuck that what was really useful.Thanks again
Sid