Feature #6561

?= operator

Added by Vlad Moskovets almost 2 years ago. Updated over 1 year ago.

[ruby-core:45518]
Status:Rejected
Priority:Normal
Assignee:-
Category:-
Target version:next minor

Description

I have feature proposition to add new opearator ?= its like ||= but assigns only when variable is not defined
So it should be shortcut for

@var ?= 1

eq

defined?(@var) ? @var : @var = 1

It should useful for caching nil'able or false'able items


Related issues

Duplicates ruby-trunk - Feature #6023: Add "a ?= 2" support for meaning "a = a.nil? ? 2 : a" Rejected 02/15/2012

History

#2 Updated by Rodrigo Rosenfeld Rosas almost 2 years ago

Would this be valid only for instance variables or any variable?

#3 Updated by Nobuyoshi Nakada almost 2 years ago

rosenfeld (Rodrigo Rosenfeld Rosas) wrote:

Would this be valid only for instance variables or any variable?

Only for instance variables, class variables, and global variables.
"undefined local variable" makes no sense.

#4 Updated by Rodrigo Rosenfeld Rosas almost 2 years ago

exactly, I was just wanting to make sure. My other proposition for ?= would work for local variables as well, although it would always evaluate the expression if the current value is null while this proposition will only evaluate it once.

For example, suppose a method like this:

def mymethod something = nil, somethingelse = nil
myvar = something || somethingelse
my_var ?= begin
...
end
end

Yeah, I know we could do "... || something_else || begin", but #6023 would allow false values to prevent the begin-end block execution.

The other approach would be something like:

myvar = begin
...
end if my
var.nil?

Or

if myvar.nil?
my
var = begin
...
end
end

I'm not strictly defending #6023 because I don't remember needing something like this yet (that's why I couldn't think in a concrete example) as what motivated me to ask for such feature was to be able to cache "false" values in my instance variables, so both #6023 and #6561 would work for me.

I'm just stating what are the major differences between them...

#5 Updated by Yutaka HARA over 1 year ago

  • Target version changed from 2.0.0 to next minor

#6 Updated by Nobuyoshi Nakada over 1 year ago

  • Status changed from Open to Rejected

I'm not against this feature concept, but '?=' conflicts with existing syntax.
You have to propose different syntax.

Also available in: Atom PDF