How to increment an Integer variable by X without instantiating a new object

How can I increment an Integer variable over X without creating a new instance of the object?

+= does not work because:

ree-1.8.7-2010.02 > x = 1
1
ree-1.8.7-2010.02 > x.object_id
3
ree-1.8.7-2010.02 > x += 1
2
ree-1.8.7-2010.02 > x.object_id
5
+3
source share
5 answers

You can not. Not in Ruby, and not in any other programming language that I know of.

An object that represents a mathematical number 1will always matter 1. Mutating an object that represents a mathematical number 1in order to suddenly get a value 2would be insane, because now suddenly 1 + 1 == 4.

+2
source

Extend the example. Try the following:

x = 2
y = 1 + 1

x.object_id
y.object_id

. Ruby , ++ Java ( ).

, x , . , .

+2

Bignum s

begin
  a = 1234567890
  puts a.object_id
  b = 1234567890
  puts b.object_id
end

10605136
10604960
0

, . Ruby.

(1..16000).each do
  (1..16000).each do
  end
end

30-40 (Lenovo T400, Virtualboxed Ubuntu), - .

0

:

class Variable
  def initialize value = nil
    @value = value
  end

  attr_accessor :value

  def method_missing *args, &blk
    @value.send(*args, &blk)
  end

  def to_s
    @value.to_s
  end

  # here the increment/decrement part
  def inc x = 1
    @value += x
  end

  def dec x = 1
    @value -= x
  end
end

x = Variable.new 1
puts x               #=> 1
puts x.object_id     #=> 22456116 (or whatever)

x.inc
puts x               #=> 2
puts x.object_id     #=> 22456116

x.inc 3
puts x               #=> 5
puts x.object_id     #=> 22456116

" " .

0

Source: https://habr.com/ru/post/1776444/


All Articles