Have you ever been in a situation where you have to remember the order of the parameter while initializing an object? This a dependency, that can be easily overcome by using a hash. Enough talk, let's see the code
Before
class Employee
def initialize(name, age, gender, department)
@name = name
@age = age
@gender = gender
@department = department
end
end
employee = Employee.new('Mat', 50, 'M', 'Dev')
=> #<Employee:0x00007fa700803d20 @name="Mat", @age=50, @gender="M", @department="Dev">
After
class Employee
def initialize(args)
@name = args[:name]
@age = args[:age]
@gender = args[:gender]
@department = args[:department]
end
end
employee = Employee.new(age: 50, department: 'Dev',name: 'Mat', gender: 'M')
=> #<Employee:0x00007fa6fc8ab060 @name="Mat", @age=50, @gender="M", @department="Dev">
As you can see above the order doesn't matter anymore. You don't to remember parameter order to create an employee object. What if while initializing an object you have to set a default value. For this it's better to use ruby's in build method called fetch for hash
class Employee
def initialize(args)
@name = args.fetch(:name)
@age = args.fetch(:age)
@gender = args.fetch(:gender)
@department = args.fetch(:department, "dev")
end
end
employee = Employee.new(name: 'Mat', age: 50, gender: 'M')
=> #<Employee:0x00007fa6fe8a1f18 @name="Mat", @age=50, @gender="M", @department="dev">
Hope this quick tip was helpful. Share your tips in comments. Let me know if you are interested in more such tips and best practices.
Top comments (0)