1. To create local variables in ruby dynamically.Use eval method in rubyree-1.8.7-2010.01 > eval("local=4") => 4 ree-1.8.7-2010.01 > p local4ree-1.8.7-2010.01 > eval("local_#{1}=4") => 4 ree-1.8.7-2010.01 > puts local_142. To create & get instance variables dynamically in ruby.instance_varaiable_set & instance_varaiable_get methods are provided and no need to do it using eval.ree-1.8.7-2010.01 > (0..3).each do |i|ree-1.8.7-2010.01 > instance_variable_set("@instance_#{i}", i*i+1)ree-1.8.7-2010.01 ?> … Continue reading Dynamic creation of variables in ruby
Author: sandipransing
Web Developer #ruby #rails #JS
Eval method in ruby
Eval method in ruby executes string/expression passed as parameter.Example:ree-1.8.7-2010.01 > eval("5+3") => 8 ree-1.8.7-2010.01 > eval("a=5") => 5 ree-1.8.7-2010.01 > eval("b||=a") => 5 Its part of ruby meta-programming and not recommended approach unless there is no any alternative to do.
has_many => through association for rails polymorphic model
Example of polymorphic association using has_many, through, source.class student has_many :posts, :as => authorendclass teacher has_many :posts, :as => authorendclass post belongs to :author, :polymorphic => trueendclass division has_many :students has_many :student_posts, :through => :students, :source => :postsendruby script/consolediv = Division.firstdiv.student_postsCheers !S@ndip
