Feature #20914
closedConstructor Parameter Shortcuts
Description
Constructor Parameter Shortcuts¶
I propose adding a new syntax to simplify the constructor definition in the classes. Defining a constructor often involves repetitive assignments of parameters to instance variables. This pattern is verbose and can easily become cumbersome, especially in classes with many instance variables. The proposed syntax allows instance variables to be automatically assigned from constructor arguments, improving code clarity and brevity.
Basic Usage:
-
Current:
class User def initialize(name, age, email = nil) @name = name @age = age @email = email end end
-
Proposed:
class User def initialize(@name, @age, @email = nil) = end
Named Parameters:
-
Current:
class Product def initialize(name:, price:, description: 'No description available') @name = name @price = price @description = description end end product = Product.new(name: 'Laptop', price: 1000)
-
Proposed:
class Product def initialize(@name:, @price:, @description: 'No description available') = end product = Product.new(name: 'Laptop', price: 1000)
Mixing Named and Positional Parameters:
-
Current:
class Booking def initialize(date, time, customer:, notes: '') @date = date @time = time @customer = customer @notes = notes end end booking = Booking.new('2023-04-01', '14:00', customer: 'Alice', notes: 'First-time client')
-
Proposed:
class Booking def initialize(@date, @time, @customer:, @notes: '') = end booking = Booking.new('2023-04-01', '14:00', customer: 'Alice', notes: 'First-time client')
Updated by mame (Yusuke Endoh) 24 days ago
- Related to Feature #5825: Sweet instance var assignment in the object initializer added
Updated by nobu (Nobuyoshi Nakada) 24 days ago
def initialize(@name, @age, @email = nil) =
What is the equal sign at the end?
nil
is missed?
Updated by artemb (Artem Borodkin) 23 days ago · Edited
You’re absolutely right; this part does seem ambiguous. I initially added it as an empty block, modeled after the short syntax, like this:
def initialize(name, age, email = nil) = (@name, @age, @email = name, age, email)
What do you think about this option:
def initialize(@name, @age, @email = nil) = ()
The nil
is also possible
def initialize(@name, @age, @email = nil) = nil
Updated by mame (Yusuke Endoh) 23 days ago
What do you think about this option:
Then this proposal is almost the same as #5825.
Updated by artemb (Artem Borodkin) 23 days ago
Thank you! This appears to be literally the same proposal, so it can be closed.
I will review #5825 and follow for updates.