3

C# has a null-conditional operator that works like this

SomeObject?.SomeParam

If SomeObject is null, then the result of that expression will be null rather than throwing a null reference exception. Does something like this exist in Ruby?

Nashenas
  • 1,583
  • 1
  • 18
  • 25

2 Answers2

8

Yes. Use &. to call a method.

some_value&.some_method

If some_value is nil, then some_method will not be executed, and the return value of the expression will be nil. Otherwise, some_method will be called as with when called with ..

sawa
  • 160,959
  • 41
  • 265
  • 366
0

If you are using Rails or ActiveSupport there is try, but there is nothing in the Ruby stdlib.

Paul A Jungwirth
  • 22,072
  • 12
  • 71
  • 90