I have this line of code in a project I am looking at -
cta = send(state + '_cta') || +''
What does the +''
do?
+''
is the unary +
operator applied to the string literal ''
and the unary +
on strings:
+str → str (mutable)
If the string is frozen, then return duplicated mutable string.If the string is not frozen, then return the string itself.
It is common to put # frozen_string_literal: true
in your Ruby files so that all string literals (such as ''
) are frozen (i.e. immutable). So ''
is often an immutable string but +''
is a mutable version of ''
.
That means that this:
cta = send(state + '_cta') || +''
should leave a mutable string in cta
.
As an aside, if send(state + '_cta')
should give you a String
or nil
then you could also say:
cta = send(state + '_cta').to_s
since NilClass#to_s
gives you an unfrozen ''
. If send(state + '_cta')
can return false
then the +''
and to_s
versions are different of course.
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