Project

General

Profile

Actions

Bug #13781

closed

Should the safe navigation operator invoke `nil?`

Added by ioquatix (Samuel Williams) over 6 years ago. Updated over 6 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:82236]

Description

In the following example:

class Later < BasicObject
	def initialize(&block)
		raise ::ArgumentError, "Block required" unless block
		
		if block.arity > 0
			raise ::ArgumentError, "Cannot store a promise that requires an argument"
		end
		@block  = block
	end
	
	def __resolve__
		@result ||= @block.call
	end
	
	def nil?
		__resolve__.nil?
	end
	
	def respond_to?(name)
	  __resolve__.respond_to?(name)
	end
	
	def method_missing(name, *args, &block)
		__resolve__.__send__(name, *args, &block)
	end
end

Person = Struct.new(:name, :age)

person = Later.new do
  nil # Person.new("Froob", 200)
end

puts person.nil?
puts person&.name

The code fails because person is a proxy object.

If safe navigation operator invoked nil? it should work. But, it's not clear exactly how the implementation should behave, or whether it's possible to implement this style of proxy.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0