本文介绍了为什么`a.is_a?数组&&!a.empty?`引发NoMethodError吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python开发人员,我刚刚开始学习Rails,所以这可能是一个讨厌的问题.我在代码中发现了一些令人惊讶的行为:

I'm a Python developer and I just started learning Rails, so this might be a noobish question. I found some surprising behavior in my code:

<!-- render flash message array if set -->
<% if flash[:notice].is_a? Array && !flash[:notice].empty? %>

这将导致以下错误:未定义的方法空?"对于nil:NilClass

在本节的第二部分中,Ruby似乎不应调用 .empty?.我确认短路评估可以在其他情况下使用:

It seems like Ruby should not be calling .empty? in the second part of this clause. I confirmed that short-circuit evaluation works in other cases:

# this is more what I expected
[3] pry(main)> a = nil
=> nil
[5] pry(main)> !a.nil? && a.empty?
=> false
...
[6] pry(main)> a = 1
=> 1
[7] pry(main)> !a.nil? && a.empty?
NoMethodError: undefined method `empty?' for 1:Integer
from (pry):7:in `__pry__'

任何人都知道为什么会发生这种现象吗?似乎仅在使用 is_a?而不是其他运算符时触发.

Anyone know why this behavior is happening? Seems to only trigger when I use is_a? and not the other operators.

推荐答案

之所以发生这种情况,是因为您使用空格而不是 is_a?函数的参数使用方括号,因此rails试图发送整个东西作为参数.像这样尝试

This is happening because you are using space and not brackets for the parameters of is_a? function so rails is trying to send the whole thing as a parameter. Try it like this

<% if flash[:notice].is_a?(Array) && !flash[:notice].empty? %>

说明:

当您编写 flash [:notice] .is_a时?数组&&!flash [:notice] .empty?导轨将其解释为 flash [:notice] .is_a?(Array&!flash [:notice] .empty?)所以 Array 评估为 true ,并评估!flash [:notice] .empty?会引发异常.

when you write flash[:notice].is_a? Array && !flash[:notice].empty? rails interpret it like flash[:notice].is_a?(Array && !flash[:notice].empty?) so Array is evaluated as true and !flash[:notice].empty? is evaluated which raises the exception.

这篇关于为什么`a.is_a?数组&amp;&amp;!a.empty?`引发NoMethodError吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 21:46