String(42) 在 Ruby 中起什么作用?
为什么我不能这样做?
>> s = String
>> s(42)
s(42)
NoMethodError: undefined method `s' for main:Object
from (irb):86
from /home/sam/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
下一个。
>> String.new 42
String.new 42
TypeError: can't convert Fixnum into String
from (irb):90:in `initialize'
from (irb):90:in `new'
from (irb):90
from /home/sam/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
如果 String.new 不能,String() 如何将 Fixnum 转换为 String?我假设 String() 调用 to_s。但是,除了要复制的字符串之外,String.new 还在寻找什么呢? new 是 dup 的别名吗?
Why cant I do this?
>> s = String
>> s(42)
s(42)
NoMethodError: undefined method `s' for main:Object
from (irb):86
from /home/sam/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
Next.
>> String.new 42
String.new 42
TypeError: can't convert Fixnum into String
from (irb):90:in `initialize'
from (irb):90:in `new'
from (irb):90
from /home/sam/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
How does String() convert a Fixnum to a String if String.new cannot? I assume String() calls to_s. But then what is String.new looking for besides a string to copy? Is new an alias for dup?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
s(42)
在您的示例中不起作用的原因是,有一个名为String
的常量(指向该类)以及一个名为 < code>String (使用to_s
将参数转换为字符串)。当您执行s = String
时,s
现在将指向与String
相同的类。但是,当您调用s(42)
时,Ruby 将查找名为s
的方法,该方法不存在,并且您会收到错误。这里的关键是,在 ruby 中,可以存在同名的变量或常量和方法,但它们之间没有任何关系。
String(42)
和String.new(42)
之间行为不同的原因是String
调用to_s
和String.new
调用to_str
。The reason that
s(42)
does not work in your example, is that there is a constant namedString
(which points to the class) as well as a method namedString
(which converts the argument to a string usingto_s
). When you dos = String
,s
will now point to the same class asString
. However when you calls(42)
, ruby will look for a method nameds
, which does not exist and you get an error.The key here is that in ruby there can be a variable or constant and a method with the same name without them having anything to do with each other.
The reason for the differing behaviour between
String(42)
andString.new(42)
is thatString
callsto_s
andString.new
callsto_str
.如果您只想要一个包含值“42”的字符串,则只需
s = "42"
即可。如果您已有一个要存储为字符串的 Fixnum,
s = some_fixnum.to_s
即可实现。If you just want a string with the value "42" in it, then
s = "42"
is all you need to do.If you already have a Fixnum that you want to store as a string,
s = some_fixnum.to_s
will do it.