From: gabriele renzi Date: 2004-01-19T08:15:04+09:00 Subject: Re: setting instance variable "dynamically" il Sun, 18 Jan 2004 18:26:22 +0100, Bauduin Raphael ha scritto:: >I saw in the pickaxe there's a way to call methods dynamically, with >send("method_name"): > >"test".send("length") # 4 > >What I want to do is set a variable this way. Is it possible? > >I'm working on a translation tool for a website. rows returned >are of the form: >["id", "language", "value"] > >the value of the language field is the identical to the member variable >that will contain the row (wrapped in an object actually). > >I thought of something like this: > >class Term >attr :query, :fr, :nl, :en > def initialize(dbh, id) > @query = "select * from translations where id='#{id}'" > dbh.select_all(query) do |row| > self.send(row[1].to_s)=Translation.new(row) > end > end > def get_french() > @fr.value > end >end > >But that isn't accepted. >Does anyone have the solution? >> class C >> def initialize >> @a,@b=10,20 >> end >> end => nil >> ary=['a','b'] => ["a", "b"] >> c=C.new => # >> c.send("a",10) NoMethodError: undefined method `a' for # from (irb):8:in `send' from (irb):8 >> class C >> def initialize >> @a,@b=10,20 >> end >> attr_accessor :a, :b >> end => nil >> c.send("a",10) ArgumentError: wrong number of arguments(1 for 0) from (irb):15:in `a' from (irb):15:in `send' from (irb):15 >> c.send("a"+"=",10) => 10 >> c.a => 10 you may even use instance_eval("@a="+value.to_s)