Surprising(?) behaviour of the comma operator

F

Frank Schmitt

Hi!

I just stumbled over a (at least for me) surprising behaviour
of the comma (',') operator:

irb(main):001:0> a,b = 1,2
[1, 2]
irb(main):002:0> puts a.class, b.class
Fixnum
Fixnum
nil

Ok, no surprises so far. Here we go:

irb(main):003:0> a=1, b=2
[1, 2]
irb(main):004:0> puts a.class, b.class
Array
Fixnum
nil

that is, a=1, b=2 creates an *Array* a instead of a Fixnum.
I don't think this is a bug, since others surely have spotted
this before me, but what's the rationale behind this?

kind regards
frank
 
N

nobu.nokada

Hi,

At Mon, 8 Dec 2003 18:32:03 +0900,
Frank said:
I just stumbled over a (at least for me) surprising behaviour
of the comma (',') operator:

Ruby has no comma operator like C.
irb(main):003:0> a=1, b=2
[1, 2]
irb(main):004:0> puts a.class, b.class
Array
Fixnum
nil

If you really want to use multi-statement, use semicolon (;)
instead.
 
H

Hal Fulton

Hi,

At Mon, 8 Dec 2003 18:32:03 +0900,
Frank said:
I just stumbled over a (at least for me) surprising behaviour
of the comma (',') operator:


Ruby has no comma operator like C.

irb(main):003:0> a=1, b=2
[1, 2]
irb(main):004:0> puts a.class, b.class
Array
Fixnum
nil


If you really want to use multi-statement, use semicolon (;)
instead.

Correct of course. To clarify a little for the original poster,
the statement is equivalent to:

a = [1, b=2]



Hal
 
F

Frank Schmitt

Hi,

At Mon, 8 Dec 2003 18:32:03 +0900,
Frank said:
I just stumbled over a (at least for me) surprising behaviour
of the comma (',') operator:

Ruby has no comma operator like C.
irb(main):003:0> a=1, b=2
[1, 2]
irb(main):004:0> puts a.class, b.class
Array
Fixnum
nil

If you really want to use multi-statement, use semicolon (;)
instead.

Normally I don't use multi-statements, but (coming from C++) I
wrote

def initialize(a,b)
@a = a, @b = b
end

Writing

def initialize(a,b)
@a,@b = a,b
end

instead is no big deal, I just have to remember it :)

Thanks to all for the quick responses & kind regards
frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top