开发者

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.开发者_C百科8.7-2010.02 > x.object_id
5


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.


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.


It gets worse with Bignums

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

gave me

10605136
10604960


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜