I want to load a parameters hash with the contents of some instance
variables, but only if they are defined.
Watch out: “only if they are defined” is not the same as “only if they
are not nil or false”. If you want the former, then this might be what
you are looking for:
class C
NAV_VARS = %w{ @prefix@category_id@page }
NAV_VAR_KEYS = NAV_VARS.inject({}) {|h,v| h[v] =
v.delete("@").to_sym; h}
def nav_params
(instance_variables & NAV_VARS).inject({}) do |params,var|
params[NAV_VAR_KEYS[var]] = instance_variable_get(var)
params
end
end
end
c = C.new
c.instance_eval do @prefix = “foo” @page = false
end
p c.nav_params # ==> {:prefix=>“foo”, :page=>false}
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.