replacing referenced Integer value in Ruby like String#replace does

怎甘沉沦 提交于 2019-12-24 00:57:37

问题


i have following code:

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

mystring = "b"

mymethod(mystring) 

p mystring # => "a"

but i want to perform same with Integer

is that possible?


回答1:


Short answer: no.

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.

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.




回答2:


-1 for "wrong thing to do". This can be a perfectly reasonable issue -- I need to do this right now: multiple objects need a shared counter.

It seems to me that the best way is to create a wrapper class and have the integer as an instance variable:

class Counter

  def initialize(i = 0)
    @i = i
  end

  def get
    @i
  end

  def set(i)
    @i = i
  end

  def inc(delta = 1)
    @i += delta
  end

end


来源:https://stackoverflow.com/questions/14139251/replacing-referenced-integer-value-in-ruby-like-stringreplace-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!