Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing referenced Integer value in Ruby like String#replace does

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?

like image 821
Pavel K. Avatar asked Oct 29 '25 01:10

Pavel K.


2 Answers

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.

like image 152
Sergio Tulentsev Avatar answered Oct 31 '25 08:10

Sergio Tulentsev


-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
like image 42
moskyt Avatar answered Oct 31 '25 07:10

moskyt