Is there an easy way to bulk assign instance variables
def initialize(title: nil, label_left: nil, label_right: nil, color_set: nil)
@title = title
@label_left = label_left
@label_right = label_right
@color_set = color_set
end
Can I loop/iterate through the initialize arguments and assign automatically?
If you want specific variables, then not really. Using reflection here, even if it was available, would be trouble.
What you've got here is the most trivial case. Often you'll see code that looks more like this:
def initialize(title: nil, label: nil, label_width: nil, color_set: nil)
@title = title.to_s
@label = label_left.to_s
@label_width = label_width.to_i
@color_set = MyRGBConverter.to_rgb(color_set)
end
The initializer is a place where you can do any necessary conversion and validation. If some of those arguments are required to be certain values you'll have tests for that, raise
an exception on an error and so forth. The repetitive code you have here in the minimal case often gets expanded and augmented on so there's no general purpose solution possible.
That leads to code like this:
def initialize(title: nil, label: nil, label_width: nil, color_set: nil)
@title = title.to_s
unless (@title.match(/\S/))
raise "Title not specified"
end
@label = label_left.to_s
unless (@label.match(/\A\w+\z/))
raise "Invalid label #{@label.inspect}"
end
@label_width = label_width.to_i
if (@label_width <= 0)
raise "Label width must be > 0, #{@label_width} specified."
end
@color_set = MyRGBConverter.to_rgb(color_set)
end
If you really don't care about which arguments you're taking in then you can do this in Ruby 2.3 with the new keyword-arguments specifier **
:
def initialize(**options)
options.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
Note that's potentially dangerous if those values are user supplied, so you might want to white-list them somehow:
VALID_OPTIONS = [ :title, :label_left, :label_right, :color_set ]
def initialize(**options)
options.each do |key, value|
raise "Unknown option #{key.inspect}" unless (VALID_OPTIONS.include?(key))
instance_variable_set("@#{key}", value)
end
end
Where you're seeing a lot of these arguments being passed in on a regular basis you might want to evaluate if creating some kind of struct-like object and passing that through might be a better plan. It depends on how your code works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With