[英]Ruby class method behaviour
考慮下面的代碼塊:
class A
def self.a(b)
if b > 0
b * b
end
end
end
現在調用方法如下:
2.3.0 :015 > A.a(2)
=> 4
2.3.0 :016 > A.a(0)
=> nil
為什么在傳遞0作為參數時無效?
如果要返回除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
另外,如果希望if b >=0
則可以將條件修改為if b >=0
如果沒有前面提到的返回值,則所有ruby方法默認都返回last
語句/表達式。 所以,就您而言,
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.
如@dstrants所指定,您可以添加else
以查看一些輸出,或者可以執行以下操作(無需else
子句),
class A
def self.a(b)
if b > 0
return b * b
end
return "Value <= 0"
end
end
這將導致輸出非nil
。
ps在絕對要使用靜態方法之前,不要使用靜態方法( self
方法)!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.