[英]Ruby class method behaviour
Consider below chunk of code: 考虑下面的代码块:
class A
def self.a(b)
if b > 0
b * b
end
end
end
Now calling method a as below: 现在调用方法如下:
2.3.0 :015 > A.a(2)
=> 4
2.3.0 :016 > A.a(0)
=> nil
Why nil on passing 0 as argument? 为什么在传递0作为参数时无效?
You should modify your method if you want to return anything else but nil as @cary-swoveland mentioned like: 如果要返回除nil以外的其他任何内容,则应修改方法,如@ cary-swoveland所述,例如:
class A
def self.a(b)
if b > 0
b * b
else
puts 'Calculation not possible'
# or whatever you want your method to return
end
end
end
Additionally, you can modify your conditional to if b >=0
if you want it to work for zero 另外,如果希望
if b >=0
则可以将条件修改为if b >=0
All ruby methods return last
statement/expression by default, if there is no return mentioned previously. 如果没有前面提到的返回值,则所有ruby方法默认都返回
last
语句/表达式。 So, in your case, 所以,就您而言,
A.a(0) #Last statement executed end, as 0 > 0 is false, without going in if. SO, it returns nothing, in other words null/nil.
As specified by @dstrants, you can add else
to see some output or you can do as follows (no need of else
clause), 如@dstrants所指定,您可以添加
else
以查看一些输出,或者可以执行以下操作(无需else
子句),
class A
def self.a(b)
if b > 0
return b * b
end
return "Value <= 0"
end
end
This will result in output other than nil
. 这将导致输出非
nil
。
ps Don't use static methods( self
methods), until you absolutely want to! ps在绝对要使用静态方法之前,不要使用静态方法(
self
方法)!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.