Project

General

Profile

Feature #12023

Updated by nobu (Nobuyoshi Nakada) almost 9 years ago

I've found myself writing a lot of code similar to the following, especially when writing service-style classes: 

 ~~~Ruby  
 ~~~ 
 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. 

 ~~~Ruby  
 ~~~ 
 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*` ID* to `iseq->body->param` 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!

Back