Navid Khan
Navid Khan

Reputation: 1169

What does `+''`` mean in Ruby?

I have this line of code in a project I am looking at - cta = send(state + '_cta') || +''

What does the +'' do?

Upvotes: 4

Views: 130

Answers (1)

mu is too short
mu is too short

Reputation: 434785

+'' 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.

Upvotes: 11

Related Questions