Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby dynamic object attributes, send vs instance variable set

Let's say I have a simple object. I have attr_accessors 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!

like image 863
Andrew Avatar asked Feb 04 '13 21:02

Andrew


1 Answers

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.

like image 65
Kaeros Avatar answered Sep 30 '22 21:09

Kaeros