像String#replace一样替换Ruby中引用的Integer值 [英] replacing referenced Integer value in Ruby like String#replace does

查看:101
本文介绍了像String#replace一样替换Ruby中引用的Integer值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

def mymethod(a)
  a.replace("a")
end

mystring = "b"

mymethod(mystring) 

p mystring # => "a"

但是我想对Integer执行相同的操作

but i want to perform same with Integer

有可能吗?

推荐答案

简短答案:否.

长答案:不,不可能.整数是足以不具有状态(和状态修改操作)的基本类型.每个对整数的运算都会生成一个新的整数.

Long answer: no, it's not possible. Integer is a type primitive enough to not have state (and state modifying operations). Every operation on integer generates a new integer.

可能,如果您降至C级,则可以就地修改基础价值.但是我不确定.无论如何,这似乎是一种矫kill过正,而且是错误的做法.

Probably, if you drop down to C level, you could be able to modify underlying value in-place. But I'm not sure. Anyway, this seems like an overkill and a wrong thing to do.

这篇关于像String#replace一样替换Ruby中引用的Integer值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆