Reputation: 6483
foo = 1
p +foo
This example code prints 1
just like if the +
was not there. I know -
in front of a variable gets the opposite of what the variable was (-29 becomes 29) but is there any case where a variable with a + in front of it ever does anything or can I safely remove it every time I see it? To clarify this a bit I am asking no specifically about numbers assigned to variables but any datatype in ruby.
Upvotes: 1
Views: 102
Reputation: 369428
is there any case where a variable with a + in front of it ever does anything
Yes. Every time. It calls the +@
method.
or can I safely remove it every time I see it?
No, you can't. It will change the semantics of your code: before, it will call the +@
method, after, it won't.
Whether or not that changes the outcome of your program, depends on what that method is doing. The default implementation for Numeric#+@
simply returns self
, but of course someone could have monkey-patched it to do something different.
Also, String#+@
does something more interesting: if self
is a frozen string, it will return an unfrozen, mutable copy; if self
is already mutable, it returns self
.
Other objects in the core library don't have a +@
method, so they will usually raise a NoMethodError
. If you remove the call, they won't; that is also a behavioral change.
Upvotes: 1
Reputation: 6483
I just looked it up for strings and yes it does do something for frozen strings.
If the string is frozen, then return duplicated mutable string.
If the string is not frozen, then return the string itself.
static VALUE
str_uplus(VALUE str)
{
if (OBJ_FROZEN(str)) {
return rb_str_dup(str);
}
else {
return str;
}
}
Upvotes: 4
Reputation: 22926
+
is both a unary operator (one argument) and a binary operator (two arguments). It is defined on the Numeric
class. Unary operators are defined using @
suffix to differentiate from the binary operator.
Unary Plus—Returns the receiver.
This is the source for the method:
num_uplus(VALUE num)
{
return num;
}
So to answer your question,
Does + in front of a variable in ruby ever do anything?
NO, for Numeric
values.
Upvotes: 6