From: Josh Cheek Date: 2009-11-13T09:45:05+09:00 Subject: Re: newbie ..need help with metaprogramming.. --000e0cd171d27bd1ae047835f83a Content-Type: text/plain; charset=ISO-8859-1 On Thu, Nov 12, 2009 at 6:05 PM, Dhaval wrote: > hi, i wrote a small code to check metaprogramming in ruby..what am i > doing wrong..can you pl help? > > class Testvar > attr_accessor :a1 > def initialize > @a1='init' > end > end > > var =":a1" > > t = Testvar.new > if t.respond_to?("#{var}") > p 'test 1- pass' > end > if t.instance_variable_set var , 'abc' > p 'test 2-pass' > end > if t.send var , 'def' > p 'test 3-pass' > end > > Try like this: class Testvar attr_accessor :a1 def initialize @a1='init' end end var = :a1 t = Testvar.new if t.respond_to?(var) puts 'test 1- pass' end t.instance_variable_set "@#{var}" , 'abc' if t.instance_variable_get("@#{var}") == 'abc' puts 'test 2-pass' end t.send "#{var}=" , 'def' if t.send(var) == 'def' puts 'test 3-pass' end --000e0cd171d27bd1ae047835f83a--