Issue #12023 has been reported by Roger Nesbitt.

----------------------------------------
Feature #12023: Allow ivars to be used as method arguments
https://bugs.ruby-lang.org/issues/12023

* Author: Roger Nesbitt
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
I've found myself writing a lot of code similar to the following, especially when writing service-style classes:

~~~
class ResizeImage
  def initialize(image, width:, height: width)
    @image = image
    @width = width
    @height = height
  end
end
~~~

Some other languages allow class property assignment on the constructor, and I thought this might be a great addition for Ruby, as Ruby likes DRY and doesn't like boilerplate.

~~~
class ResizeImage
  def initialize(@image, @width:, @height: @width)
  end
end
~~~

Please find attached a patch that implements ivars to be used as method arguments for lead, optional, post and kwarg arguments.  The tests I've implemented should demo the feature if you'd like to see how it's used.

This is my first patch to Ruby, so I'm looking forward to learning from any feedback you are able to give.  I'm not super happy with how I've implemented kwarg argument rewriting in the VM; this could be done during compilation, but I wasn't sure about adding another ID* to iseq->body->param or if the performance hit from this code would be acceptable (it's only run if a ivar argument was detected.)

I'll also note that this functionality is available to all methods, not just initialize. Although I can't see much of a use case for it on methods that aren't initialize, I also can't see the harm in allowing any method to use it.

Thanks for your consideration!

---Files--------------------------------
ruby-method-argument-ivars.diff (9.34 KB)


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

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>