我有一些看起来像这样的代码:
bal = sum_account_journal_entries(a)
if bal < 0
puts a.name +' is a credit: ' + bal.to_s
else
puts a.name +' is a debit: ' + bal.to_s
end
这里,a
有返回一个 String
的方法 name
,而 bal
是一个 Float
。
当我执行这段代码时(它是 Cucumber step_definition 的一部分,但这不是问题的根源,我们很快就会看到),我得到:
undefined method `+@' for " is a credit: ":String (NoMethodError)
这没有意义。
最佳答案
+@
是一元+
运算符,在Ruby 中,它也是一个可以覆盖的方法。例如,
class One
# Unary +
def +@
1
end
# Unary -
def -@
-1
end
end
+One.new
=> 1
-One.new
=> -1
在你的情况下,a.name
实际上是一个方法调用(ruby 中没有公共(public)字段。只有公共(public)方法),因此 Ruby 虚拟机 (YARV) 编译 a.name +' 是功劳:'
(+
和字符串之间没有空格)as
- 在字符串
' 上调用
+@
' is a credit: ' - 使用一个参数调用
a
上的方法name
:第1 步的结果
然后在运行代码时,它会在第 1 步失败并引发您看到的错误。
另一方面,a.name + ' 是一个 credit: '
(+
和字符串之间至少有一个空格),解释器将其解释为
- 不带参数调用
a.name
- 在步骤 1 的结果上调用
+
(二元+
运算符),带有一个参数' is a credit: '
关于ruby - 为什么我得到 "undefined method ` + @' for "是一个信用 : ":String (NoMethodError)" here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36586208/