How can I auto-increment a variable so each time it is used, it is incremented by one, starting with 0?
For example:
i = i+1 || 0
arr[i] = "foo"
arr[i] = "bar"
arr[i] = "foobar"
arr #=> ["foo","bar","foobar"]
I'm getting a NoMethodError undefined method '+' for nil:NilClass
A variable is just a name. It doesn't have behavior. If you want behavior, use a method:
def i
@i ||= -1
@i += 1
end
arr = []
arr[i] = 'foo'
arr[i] = 'bar'
arr[i] = 'foobar'
arr #=> ['foo', 'bar', 'foobar']
Alternatively:
_i = -1
define_method(:i) do
_i += 1
end
arr = []
arr[i] = 'foo'
arr[i] = 'bar'
arr[i] = 'foobar'
arr #=> ['foo', 'bar', 'foobar']
But really, what you have is just a very convoluted way of saying
arr = %w[foo bar foobar]
which is much clearer.
You can't. There is no way to associate variables with behaviors — in fact, doing anything with local variables besides just reading and setting them in the obvious way is nigh impossible in standard Ruby — and integers cannot change value.
However, if you are really looking to do something like this with an arrays, you can just use the << operator to push to the end of the array:
arr = []
arr << "foo"
arr << "bar"
arr << "foobar"
arr #=> ["foo","bar","foobar"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With