16
16

More than 5 years have passed since last update.

RuboCop | Style/StringLiterals

Posted at

RuboCop | Style/StringLiterals

概要

RuboCopの「Style/StringLiterals」警告について。

変数展開や文字列中にシングルクォートを含む場合など、特別な理由がなく
ダブルクォートを使っていないかチェックする。
%記法、ヒアドキュメントに関しては特別なチェックを行わない。
設定によっては、上記のようなケースでもダブルクォートを使うように
チェックすることもできる。

設定値一覧

設定対象 対象 内容 デフォルト
EnforcedStyle single_quotes 変数展開やエスケープの必要がない場合はシングルクォートを利用する
EnforcedStyle double_quotes 変数展開やエスケープの必要がない場合はダブルクォートを利用する --

StringLiterals

検証プログラム

single_line_methods.rb
print "hoge"
print "hoge'hige'"
msg = 'msg'
print "hoge#{msg}"
print 'hoge'
print %Q(hoge)
print %q(hoge)

実行結果 デフォルト の場合

.rubocop.yml
StringLiterals:
  EnforcedStyle: single_quotes
$ rubocop single_line_methods.rb
Inspecting 1 file
C

Offenses:

single_line_methods.rb:1:7: C: Prefer single-quoted strings when you don't need string interpolation or special symbols.
print "hoge"
      ^^^^^^

1 file inspected, 1 offense detected

実行結果 double_quotes に設定します

.rubocop.yml
StringLiterals:
  EnforcedStyle: double_quotes
$ rubocop single_line_methods.rb
Inspecting 1 file
C

Offenses:

single_line_methods.rb:3:7: C: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
msg = 'msg'
      ^^^^^
single_line_methods.rb:5:7: C: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
print 'hoge'
      ^^^^^^

1 file inspected, 2 offenses detected

補足

この警告は rubocop -a で修正可能です。

RuboCopまとめ記事

16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16