[英]Why is there not a destructive version of `to_s`?
Lets say: 让我们说:
n = 5
n.to_s
p n
the result of n
is still 5
rather than "5"
. n
的结果仍然是5
而不是"5"
。 What's the shortest way to replace the original variable n
with my newly converted n
without having to go through the following: 用新转换的
n
替换原始变量n
的最短方法是什么,而不必通过以下方法:
n = 5
a = n.to_s
p a
Why doesn't Ruby allow me to call to_s!
为什么Ruby不允许我调用
to_s!
on the object? 对象?
An integer cannot magically turn itself into a String. 整数不能神奇地将自己变成String。 Methods (including
!
methods) can only cause the object value to change, not the type. 方法(包括
!
方法)只能导致对象值更改,而不是类型。 Besides, integers are immutable -- the integer itself can't be modified (but the name pointing at it can be re-pointed at a new integer). 此外,整数是不可变的 - 整数本身不能被修改(但指向它的名称可以重新指向一个新的整数)。
Therefore, to_s!
因此,
to_s!
does not exist, and instead you need to rebind the variable by writing eg 不存在,而你需要通过写例如重新绑定变量
n = n.to_s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.