From: "David A. Black" Date: 2005-10-28T14:05:07+09:00 Subject: Re: "Reflecting" on my self.n00b Hi -- On Fri, 28 Oct 2005, swille wrote: > Still though, I'm unsure of whether this is a smart thing to do. Any > thoughts on that? I'd definitely like to learn the right way to do > stuff. > > class ServiceProfile > def initialize > @sp_url = nil > @sp_username = nil > @sp_password = nil > @sp_certificate = nil > @sp_owner = nil > end > That looks kind of odd. Instance variables default to nil anyway. If you're just trying to trigger them into existence, then I think the program design is probably suspect. > def load_certificate > @sp_certificate.read > end > > def call_service(&block) > end What's that method for? (It's not actually doing anything.) > end > > class MyService < ServiceProfile > def initialize > @sp_extra = nil > super > end > end > > svc_profile = MyService.new #ServiceProfile.new > sp_re = Regexp.new('^@sp_(\w+)') > > svc_profile.instance_variables.sort.reverse.each { |var| > if var.match(sp_re) > print "Enter #{Regexp.last_match(1).capitalize}: " > value = $stdin.gets.chomp > svc_profile.instance_variable_set(var, value) > end > } > > svc_profile.instance_variables.sort.reverse.each { |var| > if var.match(sp_re) > puts svc_profile.instance_variable_get(var) > end > } > The thing with the instance variable names matching a regex looks very fragile. I would recommend using real data structures. You could do something like this: class ServiceProfile SP_ITEMS = %w{url username password certificate owner } def sp_items self.class::SP_ITEMS end def initialize @sp_hash = {} end def save_service(service,value) @sp_hash[service] = value end end class MyService < ServiceProfile SP_ITEMS = SP_ITEMS.dup SP_ITEMS << "extra" end And then you could just use the data structures to get and save your data: svc_profile = MyService.new svc_profile.sp_items.each do |item| print "Enter #{item.capitalize}: " value = gets.chomp svc_profile.save_service(item,value) end David -- David A. Black dblack@wobblini.net