7stud2
(7stud --)
9 March 2014 14:30
1
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']]
···
--
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 Class: String (Ruby 2.1.1)
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
···
On Mar 9, 2014, at 10:30 AM, Arup Rakshit <lists@ruby-forum.com> wrote:
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']]
--
Posted via http://www.ruby-forum.com/\ .
--
Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/
The "`Stok' disclaimers" apply.
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
···
On Sun, Mar 9, 2014 at 3:30 PM, Arup Rakshit <lists@ruby-forum.com> wrote:
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']]
--
[guy, jim].each {|him| remember.him do |as, often| as.you_can - without end}
http://blog.rubybestpractices.com/