How to check whether an instance variable is assigned or not in ruby class? -


i have following 2 classes who's attributes set in other client class. if instance variables of these classes not assigned want make sure don't make inside of if condition such if(@lte). need explicitly check .empty?, or .nil? or .blank? etc? what's recommended check against unassigned instance variables?

# ==== range filter ==== class range < querymodel      query_hash = {}     attr_accessor :search_field, :range_criteria      def serialize         if(@search_field)             query_hash[@search_field] = @range_criteria.serialize             query_hash[:range] = self.query_hash         end     end  end  class rangecriteria < querymodel      query_hash = {}     attr_accessor :gte, :lte      def serialize         if(@gte)             query_hash[:gte] = @gte         end          if(@lte)             query_hash[:lte] = @lte         end          if(@gte != nil || @lte != nil)              return query_hash         end      end   end 

it should obvious can't determine whether or not variable assigned dereferencing variable. why? well, either trying dereference variable hasn't been assigned error (in case code break), or evaluate default object, in case won't know whether evaluated object because variable unassigned or because assigned object variable.

in ruby, both things can happen, depending on kind of variable:

unassignedconstant.nil? # boom! nameerror  @unassigned_instance_variable.nil? # => true # true because unassigned or because assigned nil? 

either way, simple logic tells calling method on variable cannot possibly answer our question. can't dereference our variable figure out whether assigned. have other way, reflective method takes variable argument (more precisely, takes the name of variable argument; methods can't take variables arguments in ruby, because variables aren't objects , can take objects arguments). thankfully, there number of such methods:

[btw: note there no corresponding method global variables, have no idea why.]

in case, want latter:

def serialize   if instance_variable_defined?(:@gte)     query_hash[:gte] = @gte   end    if instance_variable_defined?(:@lte)     query_hash[:lte] = @lte   end    unless @gte.nil? && @lte.nil?     query_hash   end end 

[note there other problems code, such query_hash being undefined, out of scope of question.]


Comments