Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

ruby

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

What does the +'' do?

like image 257
Navid Khan Avatar asked Dec 17 '22 14:12

Navid Khan


1 Answers

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

like image 87
mu is too short Avatar answered Jan 02 '23 05:01

mu is too short