kaets kaets - 4 months ago 8x
Ruby Question

self referencing an object in its assignment

I was wondering if there was a way to reference an object when assigning it to a variable. Here is an example of where this question would apply:

Let's say I wanted to assign the substring of a regex to a variable, call it i.
To assign, I could write

i = /some_regex/.to_s

and then

i = i[3...i.length]

I could also write it all in one line, like

i = /some_regex/.to_s[3.../some_regex/.to_s.length]

However, both of these examples seem somewhat redundant and the second approach could become unwieldy with big regex's or multiple method calls. Is there a way to reference the object being changed without having to rewrite everything?

Edit: Sorry for previous ambiguity.


Ruby evaluates the right side of the equals sign before setting the left side equal to it, so if i already exists you can do what you're talking about. A simple example:

i = 10
i = i + 1 # now i = 11

However, you can't use i to define itself. You could use the following two lines:

i = expression.match(/\d+[\+|-|\*|\/]/)
i = i[0..i.length - 1] # Note: this is the same as i = i[0...i.length]