As tadman says, you can't write self =. But you could write a method which takes the name of the instance variable and sets it.
You have comments saying this is 'inelegant' or 'misguided'. Although I don't share this judgement, it is good practice to write unpretentious code that uses standard conventions as much as possible. This helps others comprehend your code easily. I.e. it's probably not productive to write alternate syntaxes for such fundamental ruby methods like ||= ; other people will have to do lots of digging through your code to understand how things work.
That being said, in the interest of teaching how to make Ruby do what you want, I can suggest this Object method for this purpose:
class Object
def assign(key)
# make sure the key is a valid instance variable
unless key =~ /^[A-Za-z0-9\_]+$/
raise ArgumentError, "#{key} is not a valid ivar name"
end
if instance_variable_get("@#{key}").nil?
instance_variable_set("@#{key}", yield)
end
end
end
# example
class Foo
def set_bsd
assign("bsd", yield)
end
end
foo = Foo.new
foo.assign("my_ivar") { "val" }
foo
# => #<Foo:0x007fc2e4ccaca0 @asd=1>
foo.set_bsd { 2 }
foo
# => #<Foo:0x007fc2e4ccaca0 @asd=1 @bsd = 2>
although I would recommend against patching Object in this way - it's too generic a class and could have unintended conflicts with internal functionality. Rather, add this functionality to a custom class/module and either include the module or inherit the class.
if self.instance_of? NilClass(self.not needed, btw) withif nil?. (see Object#nil?.) For many subclass ofObject--but not all--you could writereplace yield if nil?.