1

I have the following array, that I use to later write the header on an Excel file.

fields = ["fileName", "type", "id"]

And then I have the following code that reads values from an XML:

filename = xml.xpath('//path/filename').text
type = xml.xpath('//path/type').text
id = xml.xpath('//path/id').text

The I iterate the initial array (fields) in order to set the Excel cells to the values extracted in the previous step:

row = 2
c = 1
fields.each do |content|
  ws.Cells(row,c).Value = content
  c = c + 1

I'm trying to have the array's (fields) contents to variable names instead of strings in order to be able to reuse the head fields.

Can anyone recommend a way of making it possible?

1
  • Any time you find yourself wanting to look up local variables using code, or create local variables using code, you should realize that this is "code smell" and you should instead be using a collection like a hash or an array, or a structured object. Commented May 15, 2012 at 17:11

1 Answer 1

3

This sounds like you need to use a Hash to associate field names to the values you extracted:

fields = {
  "fileName" => xml.xpath('//path/filename').text,
  "type" => xml.xpath('//path/type').text,
  "id" => xml.xpath('//path/id').text
}

row=2
c=1
fields.each do |key,value|
  ws.Cells(row,c).Value = value
  c=c+1
end
Sign up to request clarification or add additional context in comments.

3 Comments

Even better: values={}; fields.each{ |name| values[name]=xml.at_xpath("//path/#{name}").text }
@Phrogz well, I thought about that, but I assumed fileName vs. filename was not a typo.
It is a typo. Thanks for your comments... I'm pretty new to Ruby so I would try what you are proposing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.