ruby - Reading a line from a text file, splitting the string version of that line into two parts -
newbie learning ruby.
i trying take txt file , on each line take first 3 characters , assign them key, , rest of string that's keys value.
f = file.open("textfile.txt", "r") finalhash = {"key" => "data"} linestring = "" while f.gets != nil linestring = f.gets part1 = linestring.slice(0, 2) part2 = linestring.slice(3, linestring.length) finalhash[:part1] = part2 end puts finalhash
any advice appreciated!
the 2nd parameter of slice length, not end-index, change:
part1 = linestring.slice(0, 2)
to:
part1 = linestring.slice(0, 3)
if passed start index , length, returns substring containing length characters starting @ index
also don't need second parameter here (this not bug though):
part2 = linestring.slice(3, linestring.length)
this enough:
part2 = linestring.slice(3)
Comments
Post a Comment