Peña, Botp
9/6/2007 4:29:00 AM
From: John Browning [mailto:listguy@poplar.com]
# So why doesn't arg2 read its right-hand side as an array when arg3 does?
many times, if you think ruby, think ruby objects,.. then everything looks so clear...
ruby treats x (like all others) as an object, and the = as the method.
so let that x=1 be x.=(1)
irb(main):073:0> x=y=1
=> 1
irb(main):075:0> x
=> [1]
irb(main):036:0> x=1,2
=> [1, 2]
at this point ruby sees a comma, but ruby assignment treats rhs as a list, ergo array assignment(since there is no better container than array). so the comma rules. thus x=1,2 will be x.=(1,2)
irb(main):041:0> x=y=1,2
=> [1, 2]
wc is x.=(y.=(1),2)
and _not x.=(y.=(1,2))
irb(main):042:0> x
=> [1, 2]
irb(main):043:0> y
=> 1
irb(main):044:0> x=y=1,z=2,3
=> [1, 2, 3]
wc is x.=(y.=(1),z.=(2),3)
irb(main):045:0> x
=> [1, 2, 3]
irb(main):046:0> y
=> 1
irb(main):047:0> z
=> 2
irb(main):066:0> x=y=1,z=[2,a=3],b=c=4
wc is x.=(y.=(1),z.=([2,a.=(3)]),b.=(c.=(r)))
=> [1, [2, 3], 4]
irb(main):067:0> x
=> [1, [2, 3], 4]
irb(main):068:0> y
=> 1
irb(main):069:0> z
=> [2, 3]
irb(main):070:0> b
=> 4
irb(main):071:0> c
=> 4
irb(main):104:0> a
=> 3
you can simulate w ruby, of course.
irb(main):145:0> class Xclass
irb(main):146:1> @x=1
irb(main):147:1> def my=(*other)
irb(main):148:2> @x = *other
irb(main):149:2> end
irb(main):150:1> def showx
irb(main):151:2> @x
irb(main):152:2> end
irb(main):153:1> end
=> nil
irb(main):154:0> x=Xclass.new
=> #<Xclass:0xb7de1a2c>
irb(main):155:0> x.my=1
=> 1
irb(main):156:0> x.showx
=> 1
irb(main):157:0> x.my=1,2
=> [1, 2]
irb(main):158:0> x.showx
=> [1, 2]
irb(main):159:0> x.my=1,y=2
=> [1, 2]
irb(main):160:0> x.showx
=> [1, 2]
irb(main):161:0> y
=> 2
irb(main):162:0> y=nil
=> nil
irb(main):163:0> y=y
=> nil
irb(main):164:0> y=nil
=> nil
irb(main):165:0> x.my=100
=> 100
irb(main):166:0> x.showx
=> 100
irb(main):167:0> x.my=100,200
=> [100, 200]
irb(main):168:0> x.showx
=> [100, 200]
irb(main):169:0> x.my=100,y=200
=> [100, 200]
irb(main):170:0> x.showx
=> [100, 200]
irb(main):171:0> y
=> 200
i forgot about the star (*) op
irb(main):180:0> x=1,2,3
=> [1, 2, 3]
irb(main):181:0> x=[1,2,3]
=> [1, 2, 3]
irb(main):182:0> x=1,[1,2,3]
=> [1, [1, 2, 3]]
irb(main):183:0> x=1,*[1,2,3]
=> [1, 1, 2, 3]
the leading "*" expands the array and converts it to an argument list
so,
irb(main):184:0> x=1,*[1,2,3,[4]]
=> [1, 1, 2, 3, [4]]
is same as
irb(main):188:0> x=1,1,2,3,[4]
=> [1, 1, 2, 3, [4]]
arggh, it's getting longer. i must stop here.
hth.
kind regards -botp