Let's say I have a simple object. I have attr_accessor
s for the attributes I want to accept, and I want to be able to initialize with a hash of objects:
class Example
attr_accessor :foo, :bar
def initialize( attributes = {} )
attributes.each do |k,v|
...
end
end
end
In the attributes.each block above, would it be better to use send
, like so:
send "#{k}=", v
or to use instance_variable_set
, like so:
instance_variable_set "@#{k}".to_sym, v
... or to do something else entirely?
The differences I can think of are:
Using send
would be more consistent if at some point I replaced one of the attr_accessors
with a setter method.
Using send
would raise NoMethodError
if an unexpected value was passed
I'm leaning toward send
for these reasons -- I actually kind of like the possibility of NoMethodError
being raised for bogus init data. However, are there any other factors I'm overlooking here, especially performance and security considerations?
I appreciate any insight. Thanks!
My answer is to use send.
Reason: Even if the accessor is not present an instance variable will be created with instance_variable_set. As you mentioned, with send you will get a NoMethodError.
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