On 6/7/07, Todd A. Jacobs [email protected] wrote:
On Thu, Jun 07, 2007 at 01:55:23PM +0900, Ivan S. wrote:
This one is a very common mistake when someone is new to functional
languages specially when having some procedural language experience…
Many methods in functional languages don’t have side effects (don’t
Thanks. In retrospect, this is somewhat obvious. But you’re right: it
was my expectation that foo.succ was equivalent to foo+=1, rather than
simply being an expression that returned a value without modifying the
variable itself.
May I have the temerity to point out that there’s another subtle
misconception in this statement which I see a lot of Ruby nubies trip
up on, and that’s thinking that variables are objects.
An object holds state and behavior, a variable references an object.
More than one variable can reference the same object.
Modifying an object means modifying the objects state.
Modifying a variable means changing WHICH object it is referencing.
Which is done by assignment or assignment-like things such as
providing a value to the parameter of a method or block.
I would argue that: a = a.chop! doesn’t change the variable a since
it’s still referring to the same object. Consider:
a = "abc"
# changes (sets) VARIABLE a
b = a
# changes (sets) VARIABLE b
p a.object_id => -606250168
p b.object_id => -606250168
# note that its one OBJECT referenced by two VARIABLES
c = a.delete('a') => "bc"
# creates a new OBJECT leaving both VARIABLEs
# and the OBJECT they reference unchanged.
p a => "abc"
p b => "abc"
p a.object_id => -606250168
p b.object_id => -606250168
b.delete!('b')
# changes the state of the OBJECT referenced by VARIABLE b
p b => "ac"
p b.object_id => -606250168
# but leaves the VARIABLE b unchanged, it's still referencing the
same
# object albeit that object’s state has changed.
p a => “ac”
p a.object_id => -606250168
# and VARIABLE a still refers to the same (changed) OBJECT
b = c
# changes the VARIABLE b
p b.object_id => -606269188
p c.object_id => -606269188
And variable is a general term covering (local|global|instance|class)
variables as well as things like the slots in Arrays which refer to
the elements of the array.
–
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/