Nicolas Blanco
Nicolas Blanco

Reputation: 11299

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

How can I increment an Integer variable by X without creating a new object instance?

+= 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

Upvotes: 3

Views: 4087

Answers (5)

Sony Santos
Sony Santos

Reputation: 5545

You can use a helper class:

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's 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

More uses of "class Variable" here.

Upvotes: 0

karatedog
karatedog

Reputation: 2616

Execution time is really terrible even if just you organize a simple loop. Primitives shouldn't be ditched from Ruby.

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

This itself takes 30-40 seconds to complete (Lenovo T400, Virtualboxed Ubuntu), and you haven't even done something sophisticated.

Upvotes: 0

Andrew Grimm
Andrew Grimm

Reputation: 81440

It gets worse with Bignums

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

gave me

10605136
10604960

Upvotes: 0

Jörg W Mittag
Jörg W Mittag

Reputation: 369420

You can't. Not in Ruby, and not in any other programming language I am aware of.

The object which represents the mathematical number 1 will always have the value 1. Mutating the object which represents the mathematical number 1 to suddenly have the value 2 would quite simply be insane, because now all of a sudden 1 + 1 == 4.

Upvotes: 2

Berin Loritsch
Berin Loritsch

Reputation: 11463

Extend your example for a moment. Try this:

x = 2
y = 1 + 1

x.object_id
y.object_id

Every unique number will have its own identity. Ruby's object orientedness goes a bit deeper than you will find with C++ and Java (both of those have the concept of primitives and classes).

What's important is that when you query x the second time for its value the value will be what you expect. Object identifiers don't really matter unless you are the garbage collector.

Upvotes: 2

Related Questions