String(42) 在 Ruby 中起什么作用?

发布于 2024-10-15 19:54:02 字数 653 浏览 3 评论 0原文

为什么我不能这样做?

>> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

゛清羽墨安 2024-10-22 19:54:02

s(42) 在您的示例中不起作用的原因是,有一个名为 String 的常量(指向该类)以及一个名为 < code>String (使用 to_s 将参数转换为字符串)。当您执行 s = String 时,s 现在将指向与 String 相同的类。但是,当您调用 s(42) 时,Ruby 将查找名为 s 的方法,该方法不存在,并且您会收到错误。

这里的关键是,在 ruby​​ 中,可以存在同名的变量或常量和方法,但它们之间没有任何关系。

String(42)String.new(42) 之间行为不同的原因是 String 调用 to_sString.new 调用 to_str

The reason that s(42) does not work in your example, is that there is a constant named String (which points to the class) as well as a method named String (which converts the argument to a string using to_s). When you do s = String, s will now point to the same class as String. However when you call s(42), ruby will look for a method named s, 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) and String.new(42) is that String calls to_s and String.new calls to_str.

乖不如嘢 2024-10-22 19:54:02

如果您只想要一个包含值“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文