Method to call the object if the object exists
Is there a more elegant way to write this?
@on_connection_callback.call() if @on_connection_callback
It has to reference @on_connection_callback twice, which annoys me.
+3
Undistraction
source
to share
5 answers
you can write it like
@on_connection_callback.call() rescue nil
+2
VB9-UANIC
source
to share
I like things like the "andand" gem , which allows:
@on_connection_callback.andand.call()
There are other options, such as different implementations try
.
+2
Dave newton
source
to share
@on_connection_callback.instance_eval{call if self}
or
->p{p.call if p}.call(@on_connection_callback)
+1
sawa
source
to share
@on_connection_callback.call() if @on_connection_callback
great, and actually the fastest way to test. I recently did a benchmark test proving that the above is slightly faster than:
@on_connection_callback && @on_connection_callback.call()
+1
the Tin Man
source
to share
Use this little gem :
tryit { @on_connection_callback.call() }
+1
megas
source
to share