2012-05-28 64 views
1

我希望這段代碼能夠定義兩種方法,nilguardfalseguard,它們可以防止nil和false值。不定義第二種方法?

Object.class_eval do 
    @list = [false, nil] 
    @list.each do |i| 
    define_method :"#{i}guard" do |other| 
     if self == i 
     return other 
     else 
     return self 
     end 
    end 
    end 
end 

由於某種原因,它只定義了falseguard,它工作正常。爲什麼這是爲什麼它不定義其他方法?

回答

3

nil.to_s == '',所以你的第二個方法將被稱爲guard。你可能想用這樣的東西來代替:

@list = { false: false, nil: nil } 
@list.each do |s, i| 
    define_method "#{s}guard" do |other| 
    # ... 
相關問題