4 ms·
I am just not a fan of that pattern of testing the return value of an assignment statement: if (( info = details[:info] )) ...do something instead of
by LargeWu 14y ago
I am just not a fan of that pattern of testing the return value of an assignment statement:
if (( info = details[:info] ))
...do something
instead of
info == details[:info]
if info
... do something
It always looks like somebody typed = instead of ==. Or at the very least, I have to stop and think about what's going on. Yes, I get it, it lets you do something in one line of code, but I think it sacrifices readability and can make the intent ambiguous.
- xentronium 14y agoUsually there is a convention to put parens around if-assignment clause, so it is detectable.
- LargeWu 14y agoThat's interesting, I've never seen that convention in use before. Or at least never picked up on it.
- caiusdurling 14y agoSomeone on twitter asked me about that convention too - the best explanation I could find was that it's from C, where the compiler will warn you if you have a plain `if (foo = "bar")` in case you typo'd it. But putting double parens around it makes the compiler stop warning you, as you've intended the code to be that way by using a double parens. - http://stackoverflow.com/questions/3323257/double-parentheses-in-sample-code/3323400#3323400 http://stackoverflow.com/questions/3323257/double-parenthese... was the explanation I linked on twitter about it.
- xentronium 14y agoI couldn't trace the origins, but I believe it comes a long way from C. In K&R it was used quite freely in the form of while ((c = getchar()) != EOF) In this particular case it's necessary because of operators precedence, although I can't remember whether they used extra parens when it wasn't necessary. In ruby most style guides, including github's[1], are forked from bbatsov's[2], which had the bullet point about using assignment return value. [1] https://github.com/styleguide/ruby https://github.com/styleguide/ruby [2] https://github.com/bbatsov/ruby-style-guide https://github.com/bbatsov/ruby-style-guide
- rhizome 14y agoAssigning in a conditional is a very Perlish feature of Ruby.