Project

General

Profile

Feature #11034

Updated by nobu (Nobuyoshi Nakada) over 6 years ago

Hi everyone ! 

 Some time ago I was thinking about Nil Conditional Operator in Ruby (`??`). (*??*). This would be particularly useful to avoid frequent checking for nil, and should behave and look like Null Conditional Operator introduced in C# 6.0. 

 I was thinking about something like this (assume `var` *var* is nil or doesn't exist): 

 ~~~ruby ~~~ 
 var??.method1.method2(123, 345).method3 { |i| i == 1 } 
 => nil 
 ~~~ 

 When `var` *var* is nil or doesn't exist, code above should return nil or NilConditionalClass object instead of raising NoMethodError or NameError. 
 This can also work with methods (assume `var` *var* exists): 

 ~~~ruby ~~~ 
 var.method1??.method2(a, b) 
 => nil 
 ~~~ 

 When `var` *var* exists and can receive `method1`, *method1*, but `method1` *method1* returns nil - this shouldn return nil instead of raising    `NoMethodError: *NoMethodError: undefined method `method2' for nil:NilClass` nil:NilClass* 

 When `var` *var* exists and is not nil, and can receive `method1`, *method1*, and object returned by `method1` *method1* can receive `method2` *method2* this, of course should behave as expected (like version without `??` *??* operator) and return value according to implementation of method2. 

 When `var` *var* doesn't exist - this should raise NameError. 


 I tried to create gem for that (https://github.com/grzesiek/nil-conditional) but from now on, only native implementation seems reasonable. 

 What do you think about that feature ? Maybe it is already considered, but I couldn't find anything similar at Google/this issue tracker (in that case I'm sorry for duplicate). 

 Thanks in advance for feedback ! 

 Kind regards, 
  Grzegorz 

Back