LoginSignup
2
1

More than 1 year has passed since last update.

TypeError - no implicit conversion of nil into String エラーの解消

Posted at

エラーの状況

class XXX
 def XXX
  content = ''
  content << @user.name
  return content
 end
end

空のstringクラスのcontentに、@user.nameで取得した値(今回の場合はnil)を結合して、そのcontentを返すメソッドをあるモデルに定義したが、TypeError - no implicit conversion of nil into String が発生した。nilからstringへの暗黙の変換はないとのこと。

TypeErrorとは

リファレンスから引用。

メソッドの引数に期待される型ではないオブジェクトや、期待される振る舞いを持たないオブジェクトが渡された時に発生

contentのメソッド<<にnilが渡されていることが原因か?

Stringのインスタンスメソッド <<

# 例
content = ''
content << "tomato"
p content
# => "tomato"

引数で与えられた文字列を破壊的に連結するメソッド。
引数には文字列か0以上の整数を渡すことができる。

エラー解消方法 nilガード

上記より、contentのメソッド<<にnilが渡されていることがエラーの原因である。
nilガードを用いて、引数に渡すオブジェクトがnilの時は空の文字列を渡すようにする。

class XXX
 def XXX
  content = ''
  content << @user.name ||= ''
  return content
 end
end

nilガードとは、@user.nameがnilやfalseでない場合は@user.name、@user.nameがnilの場合は ||= の右側の値を代入するもの。

エラー解消までの流れ

1 エラー文をググる(TypeErrorやno implicit conversion of nil into String)
2 nilを渡してはいけないところで渡していることが原因と当たりをつける
3 デバッグなどで@user.nameがnilであることを確認する
4 Stringメソッド<<をググる
5 メソッド<<にはnilを渡せないことがわかったためnilガードを用いる

参考URL

2
1
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
2
1