I'm following Codecademy's Ruby course, about 85% done.
Over and over it asks you to create a class and pass in some parameters and make them instance variables, like this for example:
class Computer def initialize(username, password) @username = username @password = password end end
Every time, it asks you to make the exact same instance variables as the parameters you passed in.
It made me wonder if there is a Ruby way to handle this automatically, removing the need to type it all out yourself every time.
I am aware you can do
class Computer def initialize(username, password) @username, @password = username, password end end
but that's hardly less typing.
I did some searching and found that you can create a set of 'getters' using
class Song attr_reader :name, :artist, :duration end aSong = Song.new("Bicylops", "Fleck", 260) aSong.artist # "Fleck" aSong.name # "Bicylops" aSong.duration # 260
But as far as I can tell that's not really what I'm looking for. I'm not trying to auto create getters and/or setters. What I'm looking for would be something like this
class Person def initialize(name, age, address, dob) #etc # assign all passed in parameters to equally named instance variables # for example assign_all_parameters_to_instance # name, age, address and dob would now be accessible via # @name, @age, @address and @dob, respectively end end
I did some searching for ruby shortcut for assigning instance variables and alike but couldn't find an answer.
Is this possible? If so, how?