问题描述
class A
def test
"Test from instance"
end
class << self
def test
"Test from class"
end
end
end
p A.send(:test) # "Test from class"
p A.new.method(:test).call # "Test from instance"
此处符号按预期工作,但此处:
Here symbol works as expected, but here:
s="test"
s1=:s
p s1 # :s
为什么 :s 打印在这里??我不明白这背后的原因.谁能帮我解释一下?
why :s is printed here?? I dont understand the reason behind it.Can anyone please explain for me ?
推荐答案
符号是一种轻量级的字符串(尽管它们不是字符串).send()
和 method()
方法可以接受字符串或符号;一个在内部工作中转换为另一个(不确定是哪个),然后 ruby 执行具有匹配名称的方法.因此 A.send(:text)
等价于 A.text()
.如果您有一个名为 methodName = :text
的变量,您可以执行 A.send(methodName)
而不是 A.methodName()
.
Symbols are sort of lightweight strings (though they are not strings). The send()
and method()
methods can take strings or symbols; one is converted to the other in the inner workings (not sure which) and then ruby executes the method with the matching name. Hence A.send(:text)
is equivalent to A.text()
. If you had a variable named methodName = :text
, you could do A.send(methodName)
but not A.methodName()
.
符号不是变量,因此您不能为符号赋值.在您的示例中,符号 :s
与变量 s
无关(尽管它们具有相同的名称",但在其前面加上冒号使其成为符号而不是变量).您正在为变量 s
分配一个字符串值,但告诉它打印符号 :s
,它确实这样做了.
Symbols are not variables, so you can't assign a value to a symbol. In your example, the symbol :s
is unrelated to the variable s
(despite the fact that they have the same "name", preceding it with a colon makes it a symbol instead of a variable). You're assigning a string value to the variable s
but telling it to print the symbol :s
, which it does.
这篇关于将 Ruby 符号理解为方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!