Ruby 中的 to_s 与 to_str(以及 to_i/to_a/to_h 与 to_int/to_ary/to_hash) [英] to_s vs. to_str (and to_i/to_a/to_h vs. to_int/to_ary/to_hash) in Ruby
问题描述
我正在学习 Ruby,我看到了一些让我有点困惑的方法,特别是 to_s
与 to_str
(类似地,to_i
/to_int
, to_a
/to_ary
, & to_h
/to_hash
>).我读过的内容解释说,较短的形式(例如 to_s
)用于显式转换,而较长的形式用于隐式转换.
I'm learning Ruby and I've seen a couple of methods that are confusing me a bit, particularly to_s
vs to_str
(and similarly, to_i
/to_int
, to_a
/to_ary
, & to_h
/to_hash
). What I've read explains that the shorter form (e.g. to_s
) are for explicit conversions while the longer form are for implicit conversions.
我真的不明白 to_str
将如何实际使用.除了 String 之外的其他东西会定义 to_str
吗?你能给出这个方法的实际应用吗?
I don't really understand how to_str
would actually be used. Would something other than a String ever define to_str
? Can you give a practical application for this method?
推荐答案
首先请注意,所有这些都适用于每一对短"(例如 to_s
/to_i
/to_a
/to_h
) 与long"(例如 to_str
/to_int
/to_ary
)code>/to_hash
) Ruby 中的强制方法(针对它们各自的类型),因为它们都具有相同的语义.
Note first that all of this applies to each pair of "short" (e.g. to_s
/to_i
/to_a
/to_h
) vs. "long" (e.g. to_str
/to_int
/to_ary
/to_hash
) coercion methods in Ruby (for their respective types) as they all have the same semantics.
它们有不同的含义.你不应该实现 to_str
除非你的对象 像一个字符串一样作用,而不是仅仅被一个字符串表示.实现 to_str
的唯一核心类是 String 本身.
They have different meanings. You should not implement to_str
unless your object acts like a string, rather than just being representable by a string. The only core class that implements to_str
is String itself.
来自 Programming Ruby(引自 这篇博文,值得一读):
From Programming Ruby (quoted from this blog post, which is worth reading all of):
[to_i
和 to_s
] 并不是特别严格:例如,如果一个对象有某种像样的字符串表示,它可能会有一个 to_s
方法... [to_int
和 to_str
] 是严格的转换函数:只有当 [your] 对象可以自然地在每个地方使用字符串或可以使用整数.
[
to_i
andto_s
] are not particularly strict: if an object has some kind of decent representation as a string, for example, it will probably have ato_s
method… [to_int
andto_str
] are strict conversion functions: you implement them only if [your] object can naturally be used every place a string or an integer could be used.
来自 Pickaxe 的旧 Ruby 文档 有这个说:
与几乎所有类都支持的 to_s
不同,to_str
通常仅由那些行为类似于字符串的类实现.
Unlike
to_s
, which is supported by almost all classes,to_str
is normally implemented only by those classes that act like strings.
例如,除了 Integer 之外,浮动 &Numeric 实现 to_int
(to_i
相当于 to_str
),因为它们都可以很容易地替换为一个整数(它们实际上都是数字).除非您的类与 String 具有类似的紧密关系,否则您不应实现 to_str
.
For example, in addition to Integer, both Float & Numeric implement to_int
(to_i
's equivalent of to_str
) because both of them can readily substituted for an Integer (they are all actually numbers). Unless your class has a similarly tight relationship with String, you should not implement to_str
.
这篇关于Ruby 中的 to_s 与 to_str(以及 to_i/to_a/to_h 与 to_int/to_ary/to_hash)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!