Understanding send

class MyNewClass
attr_accessor :name,:place,:age
end
a=[]
1.upto(3) do
val=MyNewClass.new
val.instance_variables.each do |met|
val.send(met.delete("@")+"=",gets.chomp!)
end
a<<val
end
a.each do |val|
val.instance_variables.each do |met|
p val.send(met.delete("@"))
end
end
a.each do |val|
MyNewClass.instance_methods(false).select{
|v| v =~ /[=$]/
}.each do |met|
val.send(met,gets.chomp!)
end
end

a.each do |val|
MyNewClass.instance_methods(false).select{
|v| v =~ /[a-z]$/
}.each do |met|
p val.send(met)
end
end

hi all,
can any one tell me whats wrong with this code its not working for
val.send(met.delete("@")+"=",gets.chomp!)

if instead of val.send(met.delete("@")+"=",gets.chomp!) i give
val.name=gets.chomp!.. it works

regards
gaurav v bagga

On 11/8/06, gaurav bagga [email protected] wrote:

The problem is hidden in following lines. There is no problem with
doing send on methods.

end
You are trying to define some attributes, through attr_accessor. Now,
what attr_accessor does? It sets couple of instance methods
automatically on your class. So…if you do:
val.instance_variables.each do|x|
p x
end

You will get an empty list. Why? Because your instance variables are
not there yet. What probably you want to do is…get instance_methods
and set your instance_variables there. Until you set them
up…“val.instance_variables” will contain a empty list. and hence all
the subsequent lines will fail.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs