Reputation: 2056
How can I code an initalizer() method to form instance variables (empty or otherwise), then iterate through a set of args to set instance variables?
This is what I am thinking:
def initialize(*p)
@sid = "123asdf654"
@token = "abc123"
@bert = "1192875119"
@me = "4165551212"
@media_url = ""
@message = ""
args.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
I want to have the ability to set known instance variables (shown here), then iterate through args and either update the values of chosen instance variables, or create new ones.
Upvotes: 2
Views: 6728
Reputation: 211610
If you're going to do that you need to accept not an array of arguments (varargs style) like you've specified, but either an options hash or the new keyword-args style option.
The classic approach:
def initialize(attributes = nil)
attributes and attributes.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
The new keyword-arguments approach:
def initialize(**options)
options.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
You can also subclass OpenStruct to get behaviour like this for free.
Keep in mind there's a new option style that might be a good mix of both these approaches:
def initialize(sid: '123', token: '...', ...)
@sid = sid
@token = token
# ...
end
You can specify defaults for the named keyword arguments.
Upvotes: 5