Undefined method '+ @'

I do not understand why this does not work; all three elements must be strings.

i = 5
base = "somestring"
base = i.to_s +" #{base} " + i.to_s # => Undefined method '+@'

Why does he interpret it as a method? I thought that maybe this has to do with setting the baseequal part itself, but this seems to work:

base = "#{base}"
+4
source share
2 answers

Good question! In ruby, a method +@determines the behavior of a unary + operator. In other words, it determines what happens when you have a type expression +someSymbol.

So, in this case, he sees part of your expression, +" #{base} "and tries to apply the unary + method to a string that does not exist.

Try adding a space between +and at the beginning of your line.


, .

i = 2
i.to_s +"foo" # => NoMethodError: undefined method `+@` for "foo":String
"2" +"foo"    # => "2foo"

, ? i.to_s +"foo" i.to_s(+"foo"). , +, .


, :

i.to_s() +" #{base} " + i.to_s

"#{i} #{base} #{i}"
+9

+. +:

i.to_s + "#{base} " + i.to_s
        ^
+2

Source: https://habr.com/ru/post/1529343/


All Articles