Suppose I am having a file as below :
Variety Origin Brand Kg. pp
Yellow melons Costa Rica Black jack 10 85
Yellow melons Costa Rica Various 23
How can I read these into as array
[[‘Yellow melons’,‘Costa Rica’,‘Black jack’,‘10’,‘85’],[‘Yellow
melons’,‘Costa Rica’,‘Various’,’’,‘85’]]
On Mar 9, 2014, at 10:30 AM, Arup R. [email protected] wrote:
melons’,‘Costa Rica’,‘Various’,’’,‘85’]]
–
Posted via http://www.ruby-forum.com/.
If you have column oriented data then you can use String#unpack to
unpack the string according to a template. Numeric columns are
interesting because they are usually right justified so the last digits
line up.
The template’s content can be understood by reading
http://www.ruby-doc.org/core-2.1.1/String.html#method-i-unpack
This might help you get started:
~ ∙ pry
[1] pry(main)> DATA = <<EOS
[1] pry(main)* Variety Origin Brand Kg. pp
[1] pry(main)* Yellow melons Costa Rica Black jack 10 85
[1] pry(main)* Yellow melons Costa Rica Various 23
[1] pry(main)* EOS
=> “Variety Origin Brand Kg. pp\nYellow melons
Costa Rica Black jack 10 85\nYellow melons Costa Rica Various
23\n”
[2] pry(main)> DATA.each_line do |line|
[2] pry(main)* puts line.unpack(‘A15 A12 A10 A5 A6’).inspect
[2] pry(main)* end
[“Variety”, “Origin”, “Brand”, " Kg", “. pp”]
[“Yellow melons”, “Costa Rica”, “Black jack”, " 10", " 85"]
[“Yellow melons”, “Costa Rica”, “Various”, “”, " 23"]
Hope this helps,
Mike
–
Mike S. [email protected]
http://www.stok.ca/~mike/
The “`Stok’ disclaimers” apply.
On Sun, Mar 9, 2014 at 3:30 PM, Arup R. [email protected]
wrote:
[[‘Yellow melons’,‘Costa Rica’,‘Black jack’,‘10’,‘85’],[‘Yellow
melons’,‘Costa Rica’,‘Various’,’’,‘85’]]
Difficult to say without knowing more. Assuming a tab is the
separator here’s one approach
data = File.foreach(“your.file”).map {|line| line.split “\t”}
Cheers
robert