(由于这是评论...有点长)
事实上,你不能改变的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