[Wtr-general] OT: The original problem. Re: A small doubt in Ruby

Jonathan Kohl forum-watir-users at openqa.org
Fri Mar 9 12:42:16 EST 2007


> Jonathan Kohl mentions an opposite but similar weirdness:
> 
>  a = %w[a b c]
> b = a
>  b = %w[x y z]
> p a
>  =>
> x y z
>  p b
> =>
>  x y z
> when what was expected was this:
>  p a
> =>
> ["a", "b", "c"]
> _______________________________________________

I wouldn't characterize it as weirdness, it is just a pitfall that is common when people assign values in one way, and expect collections to behave the same way:
irb(main):001:0> a =
=> 1
irb(main):002:0> b =
=> 1
irb(main):003:0> p a
1
=> nil
irb(main):004:0> p b
1
=> nil
irb(main):005:0> b =
=> 2
irb(main):006:0> p a
1
=> nil
irb(main):007:0> p b
2
=> nil

As Marick says, variables and objects are different kinds of things. The name of the thing is not the thing itself. Variables do not contain objects, they point to them. In the array example Chris posted, we assign "a", a reference which "points" to the collection containing "["a", "b","c"]", and then we assign "b", which is a reference to "a", not the collection. That can trip people up if they are used to doing things like I posted above.
(I think I have that right, Bret or someone else could explain it better.)

 In Head First Java, Kathy Sierra explains this really well using pictures of remote controls pointing to objects. Marick had a really nice set of pictures for Scripting for Testers that explains this, but I'm not sure if it's in the book or not. 

-Jonathan
---------------------------------------------------------------------
Posted via Jive Forums
http://forums.openqa.org/thread.jspa?threadID=6791&messageID=19731#19731


More information about the Wtr-general mailing list