How can I write an array to a file with quotes around every value? - ruby

I'm trying to write an array to a CSV file. In the past, I've just used:
my_array.to_csv
and quotes be damned. But I have to conform on this particular file I'm writing to the CSV "standard". That means that, where this:
a,b,c,"d, with a comma",e
was satisfactory before, now I must output:
"a","b","d, with a comma","e"
There must be some easy way, but I can't find it.
I tried:
x.map{|v| '"' + v + '"'}.to_csv
but the file ended up with:
"""a""","""b""","""c"""
I've tried a bunch of variations on that. I ALWAYS end up with 3 quote characters.
The only thing that works is this:
fout.puts x.map{|v| "\"#{v}\"" }.to_csv.gsub('"""','"')
Which of course is hideous. Any help is appreciated!

Simply add an option:
my_array.to_csv(force_quotes:true)
You can check out more options here

better way follow
assuming a is array initially
a ="'" + a.join("','") + "'"

Related

How to delete quotation mark in text file printed

I'm honestly a novice on scilab.
I'm using print function to create .txt file with my character matrix in it.
But , when I open txt file, double quote appeared. I just want words without "".
This is how I'm using print
Compterendu(1,1)= "Medecin demandeur: "
fileresname= fullfile(RES_PATH, "compterendu.txt")
print(fileresname,Compterendu)
And, compterendu.txt was printed out like this.
Would be so grateful for any help!!
Thanks
Why do you use "print" ? After looking into the doc, yes, it is used to produce the same text as when you type the expression or the variable name on the command line. Hence it does print double quotes for strings. If you need something more basic use lower level i/o commands, like mputl.
S.

Parsing between quotes in Ruby

I'm trying to parse a string, but I'm running into trouble:
str = " #Var(\"^This is the text I want to save.\") "
What I want to parse out is: ^This is the text I want to save. Basically anything that's between the quotes.
I was trying to use a str.split()... but I'm unsure about what to specify.
Thanks
You can use regex. Here:
puts str.scan(/"(.*)"/)[0][0]
# ^This is the text I want to save.
The above regex basically looks for everything that is between " and " and returns them.
This should work - assuming you don't expect there to be multiple quoted sections. The 1 specifies the match group you want.
puts str[/"(.*)"/, 1]
# ^This is the text I want to save.
If you want to get array of arrays of different size, you may do it in two steps: .split and .scan. In your case .scan has () on two sides of |, that's why you have trouble with nil (Which supposed to be useful, but not it your case). So you have either use .flatten.compact or add the 3rd step of .delete.
Try this:
text.split("\n").map{|i|p i.scan(/'([^']+)'|(\w+)/).flatten.compact}
text.split("\n").map{|i|p i.scan(/'[^']+'|\w+/).map{|i|i.delete "'"}}

return line of strings between two strings in a ruby variable

I would like to extract a line of strings but am having difficulties using the correct RegEx. Any help would be appreciated.
String to extract: KSEA 122053Z 21008KT 10SM FEW020 SCT250 17/08 A3044 RMK AO2 SLP313 T01720083 50005
For Some reason StackOverflow wont let me cut and paste the XML data here since it includes "<>" characters. Basically I am trying to extract data between "raw_text" ... "/raw_text" from a xml that will always be formatted like the following: http://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=3&mostRecent=true&stationString=PHNL%20KSEA
However, the Station name, in this case "KSEA" will not always be the same. It will change based on user input into a search variable.
Thanks In advance
if I can assume that every strings that you want starts with KSEA, then the answer would be:
.*(KSEA.*?)KSEA.*
using ? would let .* match as less as possible.

Printing printing variable in single quoted string Ruby

I am attempting to send a tweet to twitter using the twitter_oauth gem with the following code:
client.update('.# #{tweeter}, have a nice day!')
Because of the single quotes I cannot get the variable to display but the tweet will not send if single quote are not used. Does anyone have any suggestions as to how to get this to work? thanks
Just replace the ' with ", single quoted strings don't do variable substitution and the other neat things of double quoted strings. They exist because of those missing features they are faster to parse.
If the tweet doesn't work despite using " then the problem is likely that the variable tweeter contains characters that are not allowed or in some other way invalid (maybe requiring some sort of escaping, e.g. URL or XML escaping).
Have you tried the old, java-esque way:
client.update('.# ' + tweeter + ', have a nice day!')
Or using a temporary variable:
message = ".# #{tweeter}, have a nice day!"
client.update(message)

Ruby - Writing Hpricot data to a file

I am currently doing some XML parsing and I've chosen to use Hpricot because of it's ease of use and syntax, however I am running into some problems. I need to write a piece of XML data that I have found out to another file. However, when I do this the format is not preserved. For example, if the content should look like this:
<dict>
<key>item1</key><value>12345</value>
<key>item2</key><value>67890</value>
<key>item3</key><value>23456</value>
</dict>
And assuming that there are many entries like this in the document. I am iterating through the 'dict' items by using
hpricot_element = Hpricot(xml_document_body)
f = File.new('some_new_file.xml')
(hpricot_element/:dict).each { |dict| f.write( dict.to_original_html ) }
After using the above code, I would expect that the output look like the following exactly like the XML shown above. However to my surprise, the output of the file looks more like this:
<dict>\n", " <key>item1</key><value>12345</value>\n", " <key>item2</key><value>67890</value>\n", " <key>item3</key><value>23456</value\n", " </dict>
I've tried splitting at the "\n" characters and writing to the file one line at a time, but that didn't seem to work either as it did not recognize the "\n" characters. Any help is greatly appreciated. It might be a very simple solution, but I am having troubling finding it. Thanks!
hpricot_element = Hpricot::XML(xml_document_body)
File.open('some_new_file.xml', 'w') {|f| f.write xml_document_body }
Don't use an an xml parser if you want the original xml to be written. It is unnecessary. You should still use one if you want to further process the data, though.
Also, for XML, you should be using Hpricot::XML instead of just Hpricot.
My solution was to just replace the literal '\n' characters with line breaks and remove the extra punctuation by simply adding two gsubs that looked like the following:
f.write( dict.to_original_html.gsub('\n', "\n").gsub('" ,"', '') )
I don't know why I didn't see this before. Like I said, it might be an easy answer that I wasn't seeing and that's exactly how it turned out. Thanks for all the answers!

Resources