Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto increment variable in Ruby

Tags:

variables

ruby

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

like image 215
stevenspiel Avatar asked Aug 04 '26 11:08

stevenspiel


2 Answers

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.

like image 121
Jörg W Mittag Avatar answered Aug 07 '26 02:08

Jörg W Mittag


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"]
like image 33
Chuck Avatar answered Aug 07 '26 00:08

Chuck