G
Gerard A.W. Vreeswijk
$ cat try.rb
#!/sw/bin/ruby
class Person
attr_accessor :name, :born
def initialize(args)
args.each { |k, v|
self.send "#{k}=", v
# or: send "#{k}=", v
}
end
end
p Person.new( :name=> 'John', :born=>2003 )
$ try.rb
$ #<Person:0x2a67480 @born=2003, @name="John">
$ _
Wished we had something like "self.set(k, v)". Ruby ri version 1.8b
does not seem to know of such a method, at least not of a method with
such a name.
Is it possible to set instances variables without eval or string
interpolation?
Automatic accessor construction, for example, can be done without the
help of eval and without string interpolation, namely by preceding
"self.send "#{k}=", v" with
self.class.class_eval { send :attr_accessor, k }
Thanks.
#!/sw/bin/ruby
class Person
attr_accessor :name, :born
def initialize(args)
args.each { |k, v|
self.send "#{k}=", v
# or: send "#{k}=", v
}
end
end
p Person.new( :name=> 'John', :born=>2003 )
$ try.rb
$ #<Person:0x2a67480 @born=2003, @name="John">
$ _
Wished we had something like "self.set(k, v)". Ruby ri version 1.8b
does not seem to know of such a method, at least not of a method with
such a name.
Is it possible to set instances variables without eval or string
interpolation?
Automatic accessor construction, for example, can be done without the
help of eval and without string interpolation, namely by preceding
"self.send "#{k}=", v" with
self.class.class_eval { send :attr_accessor, k }
Thanks.