Issue #11361 has been reported by masaki yamada.

----------------------------------------
Feature #11361: proposal for easy method to nil-guard for generated variable name.
https://bugs.ruby-lang.org/issues/11361

* Author: masaki yamada
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
It's easy to 'nil-guard' for normal variable.

~~~
def user
  @user ||= User.find(1)
end

~~~


but it's not simple for generated variable name.

~~~
def user(id)
  variable_name = "@user_#{id}"
  instance_variable_set(variable_name, User.find(id)) unless instance_variable_defined?(variable_name)
  instance_variable_get(variable_name)
end
~~~


I want to write it like this.

~~~
def user(id)
  instance_variable_get_or_set("@user_#{id}") { User.find(1) }
end
~~~


it can be implemented by this code.

~~~
def instance_variable_get_or_set(variable_name, &block)
  instance_variable_set(variable_name, block.call) unless instance_variable_defined?(variable_name)
  instance_variable_get(variable_name)
end
~~~



-- 
https://bugs.ruby-lang.org/