Actions
Bug #20966
closedUnary plus String warns about freezing
Description
/Users/mperham/src/sidekiq/test/profiling_test.rb:49: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
Updated by getajobmike (Mike Perham) about 10 hours ago
- Subject changed from Unary to Unary plus String warns about freezing
My code:
header = +"\x1f\x8b".force_encoding("BINARY")
Rubocop says "Use unary plus to get an unfrozen string literal."
But Ruby 3.4rc1 says:
profiling_test.rb:49: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
Should +"string"
issue a warning like that?
Updated by ufuk (Ufuk Kayserilioglu) about 10 hours ago
I think you are being tripped up by the low precedence of the unary operator, which is applied after the whole chain of calls are made. Try parenthesizing the unary plus and the string.
Updated by alanwu (Alan Wu) about 10 hours ago ยท Edited
- Status changed from Open to Rejected
+"\x1f\x8b".force_encoding("BINARY")
is parsed as
+( "\x1f\x8b".force_encoding("BINARY") )
and the warning is coming from force_encoding
.
Try (+"\x1f\x8b").force_encoding("BINARY")
or "\x1f\x8b".+@().force_encoding("BINARY")
.
A way to see the order is with ruby/debug:
$ rdbg -e 'trace call' -e 'c' test.rb
[1, 2] in test.rb
=> 1| Warning[:deprecated] = true
2| _ = +"a".force_encoding("BINARY")
=>#0 <main> at test.rb:1
(rdbg:commands) trace call
Enable CallTracer (enabled)
(rdbg:commands) c
DEBUGGER (trace/call) #th:1 #depth:2 > Warning.[]= at test.rb:1
DEBUGGER (trace/call) #th:1 #depth:2 < Warning.[]= #=> true at test.rb:1
DEBUGGER (trace/call) #th:1 #depth:2 > String#force_encoding at test.rb:2
DEBUGGER (trace/call) #th:1 #depth:3 > Warning#warn at test.rb:2
test.rb:2: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
DEBUGGER (trace/call) #th:1 #depth:3 < Warning#warn #=> nil at test.rb:2
DEBUGGER (trace/call) #th:1 #depth:2 < String#force_encoding #=> "a" at test.rb:2
DEBUGGER (trace/call) #th:1 #depth:2 > String#+@ at test.rb:2
DEBUGGER (trace/call) #th:1 #depth:2 < String#+@ #=> "a" at test.rb:2
Actions
Like0
Like0Like0Like0Like0