Ruby bug in +=?

Z

zarawesome

def addToList(x)
$list += [x];
end

def function()
addToList("a");
addToList("b");
addToList("c");
return "d";
end

$list = [];
addToList(function()); # $list = ["a","b","c","d"]

$list = [];
$list += [function()]; # $list = ["d"]!
 
J

james.d.masters

$list = [];
$list += [function()]; # $list = ["d"]!

Rewrite this longhand as:

$list = [];
$list = $list + [function()];

Which really means:

$list = [] + ["d"]
 
Z

zarawesome

Rewrite this longhand as:

$list = [];
$list = $list + [function()];

Which really means:

$list = [] + ["d"]

Yeah, figured. It's just odd, and allows for some nice obfuscated
coding.
 
H

Harry Kakueki

Rewrite this longhand as:

$list = [];
$list = $list + [function()];

Which really means:

$list = [] + ["d"]

Yeah, figured. It's just odd, and allows for some nice obfuscated
coding.
Are you expecting ["a","b","c","d"] ?
Something to look at....

$list = $list + [function()]; # ["d"]
but
$list = [function()] + $list; # ["d","a","b","c"]



Harry
 
D

dblack

Hi --

Rewrite this longhand as:

$list = [];
$list = $list + [function()];

Which really means:

$list = [] + ["d"]

Yeah, figured. It's just odd, and allows for some nice obfuscated
coding.

I'm not sure how you'd obfuscate anything using +=. As far as I know,
it's completely consistent in the way it's parsed, and thoroughly
documented. Once you know how it works, the obfuscation mysteriously
vanishes :)


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
 
R

Robert Klemme

Rewrite this longhand as:

$list = [];
$list = $list + [function()];

Which really means:

$list = [] + ["d"]

Yeah, figured. It's just odd, and allows for some nice obfuscated
coding.

I'd suggest what's making for the obfuscated code here is not +=, but
the use of a global variable and a function that has side effects.

The behavior of += doesn't seem odd to me. I'd say it's well defined.

Absolutely agree! The code presented is pretty weird and far from
straight forward IMHO.

Kind regards

robert
 

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,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top