Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method '+@'

Tags:

ruby

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}"
like image 860
chopper draw lion4 Avatar asked Dec 14 '22 22:12

chopper draw lion4


2 Answers

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}"
like image 73
JKillian Avatar answered Jan 08 '23 11:01

JKillian


Add space around + operator. Otherwise it's treated as unary + operator:

i.to_s + "#{base} " + i.to_s
        ^
like image 32
falsetru Avatar answered Jan 08 '23 11:01

falsetru