I can't understand why this is not working; all three elements should be strings.
i = 5
base = "somestring"
base = i.to_s +" #{base} " + i.to_s # => Undefined method '+@'
Why does it interpret it as a method? I thought maybe it has something to do with setting base equal to a part of itself, but this seems to work:
base = "#{base}"
                Good question! In ruby, the +@ method defines the behavior of the unary + operator. In other words, it defines what happens when you have an expression like +someSymbol.
So, in this case, it's seeing the part of your expression, +" #{base} " and trying to apply the unary + method to the string, which doesn't exist.
Try adding a space between the + and the start of your string.
What's also interesting is that this only happens in some cases.
i = 2
i.to_s +"foo" # => NoMethodError: undefined method `+@` for "foo":String
"2" +"foo"    # => "2foo"
So what's going on? i.to_s +"foo" is equivalent to i.to_s(+"foo"). And now you can see why the unary + function is being called and not the string concatenation operator.
So, you have other options to fix your code:
i.to_s() +" #{base} " + i.to_s
or even
"#{i} #{base} #{i}"
                        Add space around + operator. Otherwise it's treated as unary + operator:
i.to_s + "#{base} " + i.to_s
        ^
                        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