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.
#########
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