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


source to share


5 answers


you can write it like



@on_connection_callback.call() rescue nil

      

+2


source


I like things like the "andand" gem , which allows:

@on_connection_callback.andand.call()

      



There are other options, such as different implementations try

.

+2


source


@on_connection_callback.instance_eval{call if self}

      

or

->p{p.call if p}.call(@on_connection_callback)

      

+1


source


@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


source


Use this little gem :

tryit { @on_connection_callback.call() }

      

+1


source







All Articles