2014-09-24 33 views
1

我有一個Player類,它在initialize方法中有一個變量@hitpoints。我已經通過使用attr_accessor :hitpoints使變量可訪問。如何強制變量的輸入爲Ruby中的整數

當創建類Player的實例時,該變量確實可以訪問。但是,我想只允許寫一個整數。截至目前,我可以分配一個字符串:

conan.hitpoints = "Hello there!" 

任何想法如何實現這一點?

回答

0

另一種常見做法是轉換參數,例如,使用to_i

def hitpoints=(value) 
    @hitpoints = value.to_i 
end 

10.to_i #=> 10 
10.5.to_i #=> 10 
"10".to_i #=> 10 
"foo".to_i #=> 0 

Integer

def hitpoints=(value) 
    @hitpoints = Integer(value) 
end 

Integer(10) #=> 10 
Integer(10.5) #=> 10 
Integer("10") #=> 10 
Integer("foo") #=> ArgumentError: invalid value for Integer(): "foo" 

請注意,您不必鍵入檢查你的論點。如果對象沒有像預期的那樣行事,Ruby會早晚拋出異常:

health = 100 
hitpoints = "foo" 

health -= hitpoints #=> TypeError: String can't be coerced into Fixnum 
+0

非常感謝所有。特別感謝斯特凡:)對我來說這很好。我使用@hitpoints = Integer(value)的建議。 – 2014-09-24 11:18:27

1

你可以寫一個定製的setter吧:

def initialize(hitpoints) 
    self.hitpoints = hitpoints 
end 

UPDATE:

關於attr_accessor

class Player 
    attr_accessor :hitpoints 

    def hitpoints=(value) 
    raise 'Not an integer' unless value.is_a? Integer 
    @hitpoints = value 
    end 
end 

你也應該在你的初始化方法,而不是實例變量使用此setter 。此方法爲屬性定義了setter和getter方法。由於您在後面的代碼中定義了自己的setter,因此不需要默認的setter,並且可以使用attr_reader將其丟棄,如Stefan和Arup的評論中所建議的那樣。

雖然我對此有着相當複雜的感受,就好像你在和其他人一起工作,他會首先注意到你班上的attr_reader,並會認爲 - Hey, why is it a read_only attribute?如果它是一個新的開發者,甚至可能會導致他寫一些無意義的代碼。

我相信代碼是爲了顯示它的目的,因此我會使用attr_accessor,即使它給我method redefined警告。但這是個人喜好的問題。

+0

是的,這也是我也在想的方式..但是爲什麼還需要'attr_accessor:hitpoints'? – 2014-09-24 10:00:25

+4

使用'attr_reader:hitpoints'來避免'方法重新定義'警告 – Stefan 2014-09-24 10:00:52

+1

@BroiSatse Go Stefan說。 – 2014-09-24 10:01:54

相關問題