ruby - Is there a difference between @var = var_val and self.send("var=", var_val)? -


when initialize instance variables in initialize method, there difference between using @var = var_value , self.send("var=", var_value)? mean, there reason prefer 1 way on other reason, if means style reason?

class mysuperclass   attr_accessor :columns, :options end  class mysubclass < mysuperclass   def initialize(columns, options)     @columns = columns     @options = options   end end  class myothersubclass < mysuperclass   def initialize(columns, options)     self.send("columns=", columns)     self.send("options=", options)   end end 

there difference.

@var = x assigns instance variable. there no method call. there no virtual dispatch. there no (sane) way of intercepting assignment.

send invokes method (or "sends message"). in context, :var= assessor "setter method" wraps instance variable assignment. it's method, invoked via virtual dispatch honoring inheritance, , - including being overridden in subtypes.

the true equivalent @var = x instance_variable_set:

self.instance_variable_set(:@var, x) 

using send in case odd. use accessor directly (self.columns = columns) if intent.

as 1 "more correct" depends on level of encapsulation established - , contracts defined on types , usages thereof. err on side of accessors when subtypes involved.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -