使用安全的殿堂操作员,然后比较结果
我真的不知道该如何为自己想做的事情留下明确的标题。
我正在与ROR合作,在一个控制器中,我有此声明:
recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image] && params[:recipe][:cover_image].length > 255
因此,我试图使用安全的导航操作员进行更紧凑和易于阅读的内容,类似的事情:
recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image]&.length > 255
但是它不起作用。我明白了:
undefined method `\u003e' for nil:NilClass
问题是当零是什么时候,它会做类似的事情:nil> 255?
有办法这样做吗?安全导航操作员之后的另一个动作?
I really don't know how to put a clear title for what I am trying to do.
I am working with RoR and in a controller I have this statement:
recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image] && params[:recipe][:cover_image].length > 255
So I was trying to use the safe navigation operator for doing it a bit more compact and easy to read, something like this:
recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image]&.length > 255
But It doesn't work. I got this:
undefined method `\u003e' for nil:NilClass
The problem is that when is nil, it does something like: nil > 255 ?
Is there a way to do this? Another action after the safe navigation operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简而言之,您可以将
.to_i
添加到.length
的末尾,以确保您比较类型。例如,您遇到该错误的原因是
nilclass
没有一种称为>
的方法。但是,nilclass
确实具有.to_i
方法,该方法总是返回0
。由于>
是Integer
和0
的方法是Integer
,因此比较将 just just join 。In short, you can add
.to_i
to the end of.length
to ensure you're comparing like types. E.g.The reason you're getting that error is that
NilClass
does not have a method called>
. However,NilClass
does have a.to_i
method, which always returns0
. Since>
is a method onInteger
and0
is anInteger
, the comparison will just work.