Feature #12023
openAllow ivars to be used as method arguments
Description
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
Updated by nobu (Nobuyoshi Nakada) almost 9 years ago
- Is duplicate of Feature #5825: Sweet instance var assignment in the object initializer added
Updated by nobu (Nobuyoshi Nakada) almost 9 years ago
- Description updated (diff)
With your patch, seems that def initialize(@foo, @bar = @foo)
wouldn't work.
+ ID modified_acceptable_keywords[iseq->body->param.keyword->num];
Dynamic size array isn't allowed in C89.
Updated by nobu (Nobuyoshi Nakada) over 8 years ago
- Has duplicate Feature #12578: Instance Variables Assigned In parameters ( ala Crystal? ) added
Updated by nobu (Nobuyoshi Nakada) about 8 years ago
- Has duplicate Feature #12820: Shorter syntax for assigning a method argument to an instance variable added