(由於這是評論...有點長)
事實上,你不能改變的self
值,但是你可以在self
,這是發生了什麼事在你的榜樣更改屬性。
讓我詳細說明。假設你有一個類Foo
和你做這樣的事情:
f = Foo.new
f.bar = 3
puts f.bar # => 9
「2
」?這裏實際發生的是,您在f
上調用方法bar=
,參數1
。方法bar=
可能看起來像這樣:
class Foo
def bar=(val)
@bar = val**2 # square the given value and assign it to the instance
end # variable @bar
def bar
@bar # return the instance variable @bar -- a shortcut for this is
end
# we could get rid of the second method, though, but using attr_reader:
attr_reader :bar
end
好吧,那麼這是怎麼回事?
f = Foo.new
puts f[5] # => 10
「10
」?!是的。再次,[]
只是syntactic sugar一個普通的舊方法。事情是這樣的:
class Foo
def [](val)
val * 2 # Ruby just takes the value you put between [] and gives it to you as
end # the first parameter
end
最後:
f = Foo.new
f[:bar] = 99
puts f[:bar] # => 100
沒錯,你猜對了,這只是另一種方法調用。例如:
class Foo
@my_hash = {}
def []=(key, val) # Ruby gives us the value between the [] as the first
@my_hash[key] = val + 1 # parameter and the value after the = as the second,
end # and we use them to set a value on an internal
# instance variable...
def [](key)
@my_hash[key] # ...and we can use the "getter" to get a value from
end # the instance variable.
end
你說得對,這個東西並不是全都覆蓋在一個單一的,方便的來源,所以我希望這有助於。如果您需要進一步解釋,歡迎發表評論。
真的沒有更多的東西要學。 'self'是對當前「內部」對象的引用。您可以像處理任何其他對象一樣對'self'進行操作(但也可以直接訪問私有和受保護的方法)。如果您想了解更多信息,Google搜索第一頁上的大多數鏈接都非常穩固:http://www.google.com/search?q=ruby+self+object –
是的,但儘管您可以訪問一個由'self [0] ='指定的字符串,只會讓你獲得第一個字符。不幸的是,'self ='不是一個有效的操作。在這些鏈接中真正沒有太多關於'self [0]'或類似的東西。儘管如此,我仍然會通過互聯網和紅寶石書籍繼續跋涉。 – wulftone
我在[Metaprogramming Ruby](http://shop.oreilly.com/product/9781934356470.do)中發現了它的一些引用,但仍然沒有關於操作String的信息。 – wulftone