Rubocop: Style/EmptyLiteral not respecting frozen strings?

Created on 31 Jul 2018  路  3Comments  路  Source: rubocop-hq/rubocop

Expected behavior

No offenses on

# frozen_string_literal: true

foo = String.new
foo << 'blah'

The use of String.new is justified, since the literal version would be frozen.

Actual behavior

$ rubocop rubocop.rb 
Inspecting 1 file
C

Offenses:

rubocop.rb:3:7: C: Style/EmptyLiteral: Use string literal '' instead of String.new.
foo = String.new
      ^^^^^^^^^^

1 file inspected, 1 offense detected

Steps to reproduce the problem

Run rubocop on a file as given above.

References

This looks like a regression from https://github.com/rubocop-hq/rubocop/issues/2645

RuboCop version

Include the output of rubocop -V. Here's an example:

$ rubocop -V
0.58.2 (using Parser 2.5.1.2, running on ruby 2.5.1 x86_64-linux)

Most helpful comment

Another option is to use the unary syntax for freezing and unfreezing strings:

foo = +""

All 3 comments

FYI for this cases it's usually better do to ''.dup instead of String.new because String.new can lead to subtle bugs

irb(main):001:0> ''.dup.encoding
=> #<Encoding:UTF-8>
irb(main):002:0> String.new.encoding
=> #<Encoding:ASCII-8BIT>

Another option is to use the unary syntax for freezing and unfreezing strings:

foo = +""

@Edouard-chin @Drenmi Thanks for those hints, I didn't know that. Just noticed that new versions of rubocop already tell this:

Performance/UnfreezeString: Use unary plus to get an unfrozen string literal.

Was this page helpful?
0 / 5 - 0 ratings