Dynamic attr_accessor again using a hash


(Markus Jais) #1

hello

thanks for all your answers to my question yesterday.

I came up with this solution, where I use a hash as
an argument to initialize

···

#########
class Cla
def initialize(hash)
hash.keys.each do |key|
type.send(:attr_accessor, key)
end

            hash.each do |key, value|
                    self.instance_eval "
                            @#{key}=value
                    "
    end
    end

end
hash = { “uno” => “one”, “dos” => “two”}
c = Cla.new(hash)

puts c.uno
puts c.dos

##########

I tryed to avoid “eval” like Holden Glova recommended but
I found no way to avoid “eval” for initializing the instance
variables. I am quite content with this solution, but
if there is an even better one, please let me know.
thanks!

by the way. I showed this stuff a C++ guy and then he asked
me if I could recommend him a good Ruby book. seems like there
is one more Ruby fan out there now.

markus


(ts) #2

                        self.instance_eval "
                                @#{key}=value
                        "

Use #send
                           send("#{key}=", value)

You have created an attribute accessor, just use it :slight_smile:

Guy Decoux


(Park Heesob) #3

Hi,

“Markus Jais” mjais@web.de wrote in message
news:hQ_K8.5$VC3.915@news.ecrc.de

#########
class Cla
def initialize(hash)
hash.keys.each do |key|
type.send(:attr_accessor, key)
end

            hash.each do |key, value|
                    self.instance_eval "
                            @#{key}=value
                    "
    end
    end

end
hash = { “uno” => “one”, “dos” => “two”}
c = Cla.new(hash)

puts c.uno
puts c.dos

##########

I tryed to avoid “eval” like Holden Glova recommended but
I found no way to avoid “eval” for initializing the instance
variables. I am quite content with this solution, but
if there is an even better one, please let me know.
thanks!

How about this?

···

==========================================
class Cla
def initialize(hash)
hash.each do |key,value|
type.send(:attr_accessor, key)
send(key+’=’, value)
end
end

end

hash = { “uno” => “one”, “dos” => “two”}

c = Cla.new(hash)

Park Heesob.


(Markus Jais) #4
                    self.instance_eval "
                            @#{key}=value
                    "

Use #send
send("#{key}=", value)

You have created an attribute accessor, just use it :slight_smile:

of course!!! I tried this but had a stupid typo. maybe one
should sleep more than 2 hours a night instead of playing
with Ruby all night long :slight_smile:

Thanks for pointing me to the obvious!

markus

···

Guy Decoux