Shortcut for c = (c.nil? ? d : c+= d) ?

T

tim.griffin

Hi all,

I'm growing weary of writing checks like this:

c = (c.nil? ? d : c+= d) ?

I'd really just like to write

c+= d

and have Ruby deal with the fact that c might be nil for the assignment.

Is there a short cut I don't know about?

Thanks!
Tim
 
S

Simon Krahnke

* said:
I'm growing weary of writing checks like this:

c = (c.nil? ? d : c+= d) ?

I'd really just like to write

c+= d

and have Ruby deal with the fact that c might be nil for the assignment.

Is there a short cut I don't know about?

c ||= 0; c += d

If you can be sure that c is either a number or nil. If c is a string or
nil replace the 0 with an empty string.

c &&= c + d

would update the variable if it already is non-nil, at leaves it nil
otherwise.

mfg, simon .... nil == nil || false
 
R

Robert Klemme

Can you show a more realistic use case? Maybe the solution is in the
programming patterns that you use outside of this addition.
c ||= 0; c += d

If you can be sure that c is either a number or nil.

In that case there's also

c = c.to_i + d

Cheers

robert
 
T

tim.griffin

c ||= 0; c += d

If you can be sure that c is either a number or nil. If c is a string or

nil replace the 0 with an empty string.

c &&= c + d

would update the variable if it already is non-nil, at leaves it nil
otherwise.

Many thanks, Simon. Your first suggestion is just what I needed. A few less keystrokes.
Regards,
Tim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top