Thursday 3 March 2011

Each loop for a class or model instance variables


Sometimes we need to check all of instance variables in a class or model one by one. In this exaple we will check if a varaible is an Array or not:

your_model.instance_variables.each do |i|
if your_model.instance_variable_get(i).instance_of?(Array) then
#your code to do anything with your_model.instance_variable_get(i) what is a value
end
end

If you have an active record model, you can do:

@account = Account.first
Account.column_names.each do |i|
@account.instance_eval(i)
# row returns @account.name for example inside the loop, next @account.address and so on
end


No comments:

Post a Comment