0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

テキスト挿入時のエラー修正

0
Last updated at Posted at 2026-03-17

テキスト挿入時のエラー修正

テキスト未入力時にプレビューわ押すとエラーになっていた。

エラー文
image.png

オブジェクトにnilが入っており、文字列に変換されなかったのが原因。

nilの場合空文字になるよう修正

.rb
#修正前
sentence.body

#修正後
sentence.body ||=''

''を使う理由

1.s.to_sと ''では文字コードが違う
2.s.to_sでも空文字がはいるが、空文字を明示する書き方のほうが良いため

.rb
# '' は<Encoding:UTF-8>
p ''.to_s.encoding #=> #<Encoding:UTF-8>

# s.to_s は<Encoding:US-ASCII>
p nil.to_s.encoding #=> #<Encoding:US-ASCII>

UTF-8 でしか動かない処理に投入するのであれば,s.to_s は使ってはいけない。

参考

Ruby で s が nil か String か分らぬとき s.to_s と s || '' はどっちがいい?
[個人用メモ/nil対策]Rubyで nil.to_sは文字列に変換して文字列を返す。使うのはNG

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?