Ruby Issue Tracking System: Issueshttps://bugs.ruby-lang.org/https://bugs.ruby-lang.org/favicon.ico?17113305112016-10-28T17:39:53ZRuby Issue Tracking System
Redmine Ruby master - Bug #12881 (Closed): Double-bang (!!) raises warning on string literalhttps://bugs.ruby-lang.org/issues/128812016-10-28T17:39:53Zrrroybbbean (RRRoy BBBean)
<p>I use !!x or !!(x) to force x to true or false.<br>
I just noticed this trick raises a warning with string literals.<br>
It would be nice if this warning were not raised, since it is sometimes convenient to force some object to true or false.<br>
I first saw this in irb, but it also happens when running a script from the command line.<br>
Caveat: Although the output of my sample program suggests that double-quoted strings avoid this warning, it actually happens with !!"hi" as well as !!'hi'</p>
<p>CODE: bb.rb<br>
1 p [ '!!false', !!false ]<br>
2 p [ '!!(false)', !!(false) ]<br>
3 p [ '!!nil', !!nil ]<br>
4 p [ '!!(nil)', !!(nil) ]<br>
5 p [ '!!true', !!true ]<br>
6 p [ '!!(true)', !!(true) ]<br>
7 p [ '!![]', !![] ]<br>
8 p [ '!!([])', !!([]) ]<br>
9 p [ '!!{}', !!{} ]<br>
10 p [ '!!Object.new', !!Object.new ]<br>
11 p [ '!!(Object.new)', !!(Object.new) ]<br>
12 p [ '!!1', !!1 ]<br>
13 p [ '!!(1)', !!(1) ]<br>
14 p [ '!!0.1', !!0.1 ]<br>
15 p [ '!!(0.1)', !!(0.1) ]<br>
16 p [ '!!:a', !!:a ]<br>
17 p [ '!!(:a)', !!(:a) ]<br>
18 p [ '!!({})', !!({}) ]<br>
19 p [ '!!String.new', !!String.new ]<br>
20 p [ '!!(String.new)', !!(String.new) ]<br>
21 p [ '!!""', !!"" ]<br>
22 p [ '!!("")', !!("") ]<br>
23 p [ '!!"b"', !!"b" ]<br>
24 p [ '!!("b")', !!("b") ]<br>
25 p [ "!!''", !!'' ]<br>
26 p [ "!!('')", !!('') ]<br>
27 p [ "!!'b'", !!'b' ]<br>
28 p [ "!!('b')", !!('b') ]</p>
<p>OUTPUT<br>
bb.rb:25: warning: string literal in condition<br>
bb.rb:26: warning: string literal in condition<br>
bb.rb:27: warning: string literal in condition<br>
bb.rb:28: warning: string literal in condition<br>
["!!false", false]<br>
["!!(false)", false]<br>
["!!nil", false]<br>
["!!(nil)", false]<br>
["!!true", true]<br>
["!!(true)", true]<br>
["!![]", true]<br>
["!!([])", true]<br>
["!!{}", true]<br>
["!!Object.new", true]<br>
["!!(Object.new)", true]<br>
["!!1", true]<br>
["!!(1)", true]<br>
["!!0.1", true]<br>
["!!(0.1)", true]<br>
["!!:a", true]<br>
["!!(:a)", true]<br>
["!!({})", true]<br>
["!!String.new", true]<br>
["!!(String.new)", true]<br>
["!!""", true]<br>
["!!("")", true]<br>
["!!"b"", true]<br>
["!!("b")", true]<br>
["!!''", true]<br>
["!!('')", true]<br>
["!!'b'", true]<br>
["!!('b')", true]</p>
<p>ruby --version<br>
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]<br>
I compiled it myself from sources, running on Fedora24 amd64 workstation</p>