簡體   English   中英

Ruby類方法行為

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM