Project

General

Profile

Feature #12023

Allow ivars to be used as method arguments

Added by mogest (Roger Nesbitt) about 3 years ago. Updated about 3 years ago.

Status:
Open
Priority:
Normal
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

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

History

#1

Updated by nobu (Nobuyoshi Nakada) about 3 years ago

  • Is duplicate of Feature #5825: Sweet instance var assignment in the object initializer added
#2

Updated by nobu (Nobuyoshi Nakada) about 3 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.

#3

Updated by nobu (Nobuyoshi Nakada) over 2 years ago

  • Has duplicate Feature #12578: Instance Variables Assigned In parameters ( ala Crystal? ) added
#4

Updated by nobu (Nobuyoshi Nakada) over 2 years ago

  • Has duplicate Feature #12820: Shorter syntax for assigning a method argument to an instance variable added

Also available in: Atom PDF