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,651
  • 1
  • 21
  • 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
  • 165,429
  • 45
  • 277
  • 381
0

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

Paul A Jungwirth
  • 23,504
  • 14
  • 74
  • 93