How to dynamically initialize any arguments in Ruby ?

The implementation below is very handy when you are you are not really concerned about a number or a quality of arguments you are setting (maybe you are prototyping ? consuming 3rd party API ?)
Pretty Straightforward, here is the code :


Quick Explanation what  am I doing here:

initialize() allows us to receive *args, which fives us a  Hash from arguments that you are passing to it. I go through this hash and create instance variable of every hash key, then I assign value to this hash key. Totally dynamic. I also create attribute_accessor on a fly so I could read and write to any of those instance variables.

Note: There are edge cases not covered here, do make sure it works for your particular situation, but I think this is a good start.



Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion

Your email address will not be published. Required fields are marked *