Ka Mok - 10 months ago 40

Ruby Question

Given the expression "1 * 2 / 3 + 4"

I'm trying to write out all possible variants of the equation when implementing order of operations. Such as: "(1 * 2) / 3) + 4" and "(1 * (2 / 3)) + 4"

This is what I have now:

`expression = [1.0, "+", 2.0, "+", 3.0, "+", 4.0]`

storage = []

exp1 = expression #Make new object because insert method will overwrite expression object

storage << exp1.insert(0, "((").insert(4, ")").insert(7, ")")

But exp1's changes reflect in expression as well. I even made them in separate methods but the changes keep reflecting on expression.

How do I keep the expression object unchanged? I need to configure the original expression 5 times in total, but I'm struggling to keep it clean when I use .insert method. Reading Ruby docs, the insert method is the only one suitable to what I'm doing.

Do I have to use a different data structure to store "1 * 2 / 3 + 4" other than an array ?

Answer

Consider using `#dup`

so that you don't alter the original set:

```
expression.dup.insert(0, "((").insert(4, ")").insert(7, ")")
```

;)