DEV Community

shiva kumar
shiva kumar

Posted on

1 2

The Order doesn't matter anymore

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">


Enter fullscreen mode Exit fullscreen mode

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">

Enter fullscreen mode Exit fullscreen mode

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay