Monday, November 22, 2010

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





That's all!

6 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete

Note: Only a member of this blog may post a comment.