views:

153

answers:

1

Hi All,

I've got a bit of an odd situation. If I were using a hash, this issue would be easy, however, I'm trying to use "OpenStruct" in Ruby as it provides some decently cool features.

Basically, I think I need to "constantize" a return value. I've got a regular expression:

  textopts = OpenStruct.new()
  textopts.recipients = []
  fileparts = fhandle.read.split("<<-->>")

  fileparts[0].chomp.each{|l|
    if l =~ /Recipient.*/i
      textopts.recipients << $&
    elsif l =~ /(ServerAddress.*|EmailAddress.*)/i
      textopts.$& = $&.split(":")[1]
    end
  }

I need a way to turn the $& for "textopts" into a valid property for filling. I've tried "constantize" and some others, but nothing works. I would assume this is possible, but perhaps I'm wrong. Obviously if I were using a hash I could just do "textopts[$&] = .....".

Any ideas?

+1  A: 

Keeping the structure of your solution, this is one way to do it:

  textopts = OpenStruct.new(:recipients => [])
  fileparts = fhandle.read.split('<<-->>')

  fileparts.first.chomp.each_line do |l|
    case l
    when /Recipient.*/i
      textopts.recipients << $&
    when /(Server|Email)Address.*/i
      textopts.send "#{$&}=", $&.split(':')[1]
    end
  end

But I can't help but think that this should be a proper parser.

Jörg W Mittag
Thanks for that. Please define "proper parser". I'm basically doing a little finagling with an email and sending it via Ruby's NET::SMTP module. I'm using OptionParser to handle the command line items, but I'm reading in the actual text file myself. I'm expecting certain parameters to exist in the top of the text file and am simply grabbing those few items manually, the rest is really the email itself that will be "snatched out" and sent.
humble_coder