On Mon, Dec 24, 2012 at 12:55 AM, Paul Magnussen <[email protected]> wrote: > Thanks for all the replies. I notice also that I can force changing of > the value (as opposed to the reference) by substituting a trivial > expression for the right-hand side of the assignment, e.g. > > # g) Expression > > myStringA = "Fred Shufflebotham" > myStringB = myStringA + "" > myStringB[0,4] = "Bert" > > => myStringA = "Fred Shufflebotham" > => myStringB = "Bert Shufflebotham" > > But of course it's an utter kludge. Is there really no more elegant > way?
my_string_a = "Fred Shufflebotham" my_string_b = my_string_a.dup Note that in Ruby naming convention of local variables and method names is not CamelCase but snake_case. Paul, what you should take away from this discussion (I'll try to summarize what other's have said already): - All variables hold _references_ to objects.* - Assignment copies an object reference and stores it in a variable. - String literals are really object constructors, i.e. they create a new object whenever evaluated. (Don't worry, behind the scenes this is made efficient.) - There are immutable classes (most numeric classes, nil, TrueClass...) and mutable classes (all others including String). - Arithmetic operators return a reference to a new instance in order to make math work properly (a + b + a would return wrong results if the first + changed state of a and returned a reference to the mutated a). * Note that this is not completely true in terms of the _implementation_ of MRI but it is true from the perspective of the _language user_. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ -- You received this message because you are subscribed to the Google Groups ruby-talk-google group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at https://groups.google.com/d/forum/ruby-talk-google?hl=en
