This is a common initializer pattern:
def initialize(title, val, type)
@title, @val, @type = title, val, type
end
Is there a shortcut that is equivalent to "take every argument, create an attribute of the same name, and set the attribute equal to the argument's value"?
I'm looking for a gem-free solution.
You will lose the function to check against wrong arguments, but can do this:
def initialize(*args)
@title, @val, @type = args
end
But if you are repeatedly doing this, then your code is not right. You should better redesign your API to take named arguments:
def initialize(title:, val:, type:)
...
end
WhateverClass.new(title: "foo", val: "bar", type: "baz")
You can use Struct as mentioned above or do it dynamically like:
class MyClass
def initialize input
input.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
end
Anyways If it's my code I'll go using Struct.
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