2014-03-26 52 views
0

爲什麼不能正常工作?如何在ruby中爲一個模塊覆蓋一個類?

module Magic 
    class Fixnum 
    def div2(other) 
     self.to_f/other 
    end 

    alias :"/" :div2 
    end 
end 

module SomeModule 
    include Magic 

    1/4 == 0.25 #should be true in here 
end 

1/4 == 0.25 #should be false everywhere else 
+0

一個細節:'self.to_f'確定,但'to_f'就足夠了。 –

回答

5

您發佈的答案實際上是全球變化的Fixnum,這不是您想要的。也就是說,你的解決方案:

module Magic 
    class ::Fixnum 
    def div2(other) 
     self.to_f/other 
    end 

    alias :"/" :div2 
    end 
end 

# Yields 0.25 instead of expected 0. 
# This line should not be affected by your Fixnum change, but is. 
1/4 

對於您所描述的用例,紅寶石2.0引入refinements,你可以使用如下。請注意,using另一個模塊中的模塊在Ruby 2.0中是不可能的,但在Ruby 2.1中是不可能的。因此,要使用SomeModule中的Magic模塊,您需要使用Ruby 2.1。如果您使用的是Windows,這可能會造成問題,因爲您必須自己編譯2.1,Windows二進制文件和安裝程序仍然在2.0。

module Magic 
    refine Fixnum do 
    def /(other) 
     self.to_f/other 
    end 
    end 
end 

1/4 # => 0 
using Magic 
1/4 # => 0.25 
0

OK,我需要在頂層訪問Fixnum類,代碼應該是:

module Magic 
    class ::Fixnum 
    def div2(other) 
     self.to_f/other 
    end 

    alias :"/" :div2 
    end 
end 

這工作!

0

如果你想讓你的修改Fixnum只適用於某些地方,你可以使用refinements

module Magic 
    refine Fixnum do 
    def foo 
     "Hello" 
    end 
    end 
end 

class SomeClass 
    using Magic 

    10.foo # => "Hello" 

    def initialize 
    10.foo # => "Hello" 
    end 
end 

10.foo # Raises NoMethodError 

你原來的例子定義內MagicMagic::Fixnum)稱爲Fixnum類。它不會觸及全球Fixnum。您發佈的回覆信息::Fixnum修改了全球Fixnum課程。

相關問題