[ruby-core:120029] [Ruby master Feature#20914] Constructor Parameter Shortcuts
From:
"artemb (Artem Borodkin) via ruby-core" <ruby-core@...>
Date:
2024-11-27 22:20:23 UTC
List:
ruby-core #120029
Issue #20914 has been reported by artemb (Artem Borodkin).
----------------------------------------
Feature #20914: Constructor Parameter Shortcuts
https://bugs.ruby-lang.org/issues/20914
* Author: artemb (Artem Borodkin)
* Status: Open
----------------------------------------
# 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**:
```ruby
class User
def initialize(name, age, email = nil)
@name = name
@age = age
@email = email
end
end
```
- **Proposed**:
```ruby
class User
def initialize(@name, @age, @email = nil) =
end
```
**Named Parameters**:
- **Current**:
```ruby
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**:
```ruby
class Product
def initialize(@name:, @price:, @description: 'No description available') =
end
product = Product.new(name: 'Laptop', price: 1000)
```
**Mixing Named and Positional Parameters**:
- **Current**:
```ruby
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**:
```ruby
class Booking
def initialize(@date, @time, @customer:, @notes: '') =
end
booking = Booking.new('2023-04-01', '14:00', customer: 'Alice', notes: 'First-time client')
```
--
https://bugs.ruby-lang.org/
______________________________________________
ruby-core mailing list -- ruby-core@ml.ruby-lang.org
To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/