使用安全的殿堂操作员,然后比较结果

发布于 2025-02-10 05:42:27 字数 665 浏览 2 评论 0原文

我真的不知道该如何为自己想做的事情留下明确的标题。

我正在与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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℡Ms空城旧梦 2025-02-17 05:42:27

简而言之,您可以将.to_i添加到.length的末尾,以确保您比较类型。例如,

recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image]&.length.to_i > 255

您遇到该错误的原因是nilclass没有一种称为>的方法。但是,nilclass确实具有.to_i方法,该方法总是返回0。由于>Integer0的方法是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.

recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image]&.length.to_i > 255

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 returns 0. Since > is a method on Integer and 0 is an Integer, the comparison will just work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文