Project

General

Profile

Actions

Feature #12023

open

Allow ivars to be used as method arguments

Added by mogest (Roger Nesbitt) almost 9 years ago. Updated almost 9 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:73474]

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

ruby-method-argument-ivars.diff (9.34 KB) ruby-method-argument-ivars.diff mogest (Roger Nesbitt), 01/26/2016 08:58 AM

Related issues 3 (1 open2 closed)

Is duplicate of Ruby master - Feature #5825: Sweet instance var assignment in the object initializerAssignedmatz (Yukihiro Matsumoto)Actions
Has duplicate Ruby master - Feature #12578: Instance Variables Assigned In parameters ( ala Crystal? )RejectedActions
Has duplicate Ruby master - Feature #12820: Shorter syntax for assigning a method argument to an instance variableRejectedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0