Ruby: How to split lines read from a file into a two dimensional array? -



Ruby: How to split lines read from a file into a two dimensional array? -

for little thing, want store info in file , read in such way, have two-dimensional array @ end.

let's content of config file:

banana:yellow apple:red

this code came with:

a = file.read("config.txt") b = a.split("\n") k = array.new b.each { |x| k.push(x.split(":"))} print k

it works, certainly there must improve way this?

you can below using io::readlines , string#splt

file.readlines("config.txt").map { |str| str.split(":") }

or, using csv::read

require 'csv' csv.read("path/to/file", 'rb', :col_sep => ':') # => [["banana", "yellow"], ["apple", "red"]]

with csv, can skip lines, don't want process using alternative :skip_lines :

when set object responding match, every line matching considered comment , ignored during parsing. when set string, first converted regexp. when set nil no line considered comment. if passed object not respond match, argumenterror thrown.

suppose have file test.txt content :-

banana:yellow apple:reds #foo:biz bar:cz

now don't want read lines start #. re-write code

require 'csv' csv.read("#{__dir__}/test.txt", 'rb', :col_sep => ':',:skip_lines => /\a#/)

let's run code , see :

arup@linux-wzza:~/ruby> ruby test.rb [["banana", "yellow"], ["apple", "reds"], ["bar", "cz"]] arup@linux-wzza:~/ruby>

ruby arrays io

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -