2013-03-14 50 views
2

爲什麼singleton方法不能在FixnumBignumFloatSymbol類對象,但FalseClassTrueClass都可以定義?爲什麼不能在`Fixnum`,`Bignum`,`Float`,`Symbol`類對象中定義`singleton`方法,但是`FalseClass`和`TrueClass`可以有?

C:\>ruby -v 
ruby 2.0.0p0 (2013-02-24) [i386-mingw32] 

C:\>irb --simple-prompt 
DL is deprecated, please use Fiddle 
11111111111.class 
#=> Bignum 
class << 11111111111 ; end 
#TypeError: can't define singleton 
#  from (irb):2 
#  from C:/Ruby200/bin/irb:12:in `<main>' 

1111.class 
#=> Fixnum 
class << 1111 ; end 
#TypeError: can't define singleton 
#  from (irb):4 
#  from C:/Ruby200/bin/irb:12:in `<main>' 

11.11.class 
#=> Float 
class << 11.11 ; end 
#TypeError: can't define singleton 
#  from (irb):6 
#  from C:/Ruby200/bin/irb:12:in `<main>' 

:name.class 
#=> Symbol 
class << :name ; end 
#TypeError: can't define singleton 
#  from (irb):8 
#  from C:/Ruby200/bin/irb:12:in `<main>' 
+0

難道你不是指「實例對象」,而不是「類對象」?順便說一句,'NilClass'的實例對象也允許單例對象。 – 2013-03-17 22:19:50

回答

0

docs

有效的只有一個對於任何給定的整數值Fixnum對象的對象實例,因此,舉例來說,你不能添加一個單身的方法來一個Fixnum。

這將適用於其他原始數值類型和符號。

5

由於Ruby Docs說:

有效,對於任何給定的整數值只有一個Fixnum對象對象實例,因此,舉例來說,你不能一個單身方法添加到一個Fixnum。

同樣是真實的BignumFloatSymbol

+2

但是爲什麼不用'false','true'或'nil'? – 2013-03-17 22:20:25

+0

這是完全錯誤的:'big_fix = 4611686018427387903; big_fix.class#=> Fixnum; big1 = big_fix + 1; big1.class#=> Bignum; big2 = big_fix + 1; big1.object_id == big2.object_id#=> false'因此可以有**許多具有相同值但引用不同的Bignums。 – YoTengoUnLCD 2017-01-07 20:55:41

0

一個Singleton class的定義特徵是:它只有一個實例

  • FalseClass只有一個實例:false
  • TrueClass只有一個實例:true
  • NilClass只有一個實例:nil

這是不是一回事如,例如,FloatSymbol類;這些是而不是單身。

雖然這是事實,有這些類給定值只有一個實例:

3.14159.object_id #=> 20565057194439538 
3.14159.object_id #=> 20565057194439538 
3.14159.object_id #=> 20565057194439538 
:hello.object_id #=> 3551708 
:hello.object_id #=> 3551708 
:hello.object_id #=> 3551708 

不同,例如,它沒有這個屬性String類:

"test".object_id #=> 34347120 
"test".object_id #=> 34388680 
"test".object_id #=> 22397760 

請記住,這是而不是單例的定義。 :foo:bar是兩個不同的Symbol的實例。

這就是爲什麼singleton方法可以TrueClassFlaseClassNilClass,但不能被定義,例如,在Symbol

相關問題