From: treznick@... Date: 2015-10-23T03:58:09+00:00 Subject: [ruby-core:71169] [Ruby trunk - Feature #11537] Introduce "Safe navigation operator" Issue #11537 has been updated by Tom Reznick. Thanks for the thoughtful replies guys! That definitely helps clarify the `.?` operator Matthew Kerwin wrote: > On 23/10/2015 2:46 AM, wrote: > > > > Issue #11537 has been updated by Jeremy Evans. > > > > > > Tom Reznick wrote: > > > Hi, > > > > > > I think we may have found some unexpected behavior with the `.?` > operator. > > > > > > If I call the following: > > > > > > s = Struct.new(:x) > > > o = s.new() > > > o.x #=> nil > > > o.x.nil? #=> true > > > o.x.?nil? #=> nil > > > o.x.kind_of?(NilClass) #=> true > > > o.x.?kind_of?(NilClass) #=> nil > > > o.x.methods.include?(:nil?) #=> true > > > > > > > > > While it's arguably a bit peculiar to try to check that `nil` is `nil`, > in a `nil`-safe way, `.?kind_of?(NilClass)` could reasonably return `true`. > > > > I think it's completely expected that `nil.?kind_of?(NilClass)` returns > `nil` and not `true`. The whole point of `.?` is to return `nil` without > calling the method if the receiver is `nil`. I'm not sure if `.?` is a > good idea syntax-wise, but if you are going to have it, it shouldn't have > special cases for specific methods. > > > > I agree, or put another way: if you're testing for nil in two ways, .? has > higher priority. That makes it a programmer issue, not a ruby one. ---------------------------------------- Feature #11537: Introduce "Safe navigation operator" https://bugs.ruby-lang.org/issues/11537#change-54543 * Author: Hiroshi SHIBATA * Status: Closed * Priority: Normal * Assignee: Yukihiro Matsumoto ---------------------------------------- I sometimes write following code with rails application: ```ruby u = User.find(id) if u && u.profile && u.profile.thumbnails && u.profiles.thumbnails.large ... ``` or ```ruby # Use ActiveSupport if u.try!(:profile).try!(:thumbnails).try!(:large) ... ``` I hope to write shortly above code. Groovy has above operator named "Safe navigation operator" with "`?.`" syntax. Ruby can't use "`?.`" operator. Can we use "`.?`" syntax. like this: ```ruby u = User.find(id) u.?profile.?thumbnails.?large ``` Matz. How do you think about this? -- https://bugs.ruby-lang.org/