Mark Hubbart
10/9/2004 6:48:00 PM
On Sun, 10 Oct 2004 00:44:50 +0900, Arthur Korneyew <pustoi@spils.lv> wrote:
> Hello,
>
> I have file like this (words.txt):
>
> #
> word1 word2
> word3 word4
> word5 word6
> word7 word8
>
> How can I split words into 2D array in ruby ?
>
> I just tried:
>
> a = [[],[]]
> IO.foreach("words.txt") {|line|
> unless line.strip.empty? | (line =~ (/^\#/))
> string = line.chomp.split
> a << string
> end
> }
>
> #puts a
> puts [0][1]
>
> [root@tequila2 logs]# ./logs5.rb
> nil
The problem, as others have shown, is that you did more array
initialization than you needed. But there are also simpler ways of
doing this, which you may not have known about:
IO (and File, and String), are enumerable, like arrays and ranges.
Instead of iterating through each element, IO and String objects go
through each line. This gives you the ability to use #map on a File,
which converts it to an array of lines:
# block form automatically closes the file after the block finishes
words = File.open("words") do |file|
# file.map passes in each line, then line.split splits it into an array.
file.map{|line| line.split}
end
It appears that you want to get rid of lines that don't have exactly
two words in them, so add this line after you get the array of words:
# reject! deletes the element if the block evaluates to true
# in this case, it deletes the element if it doesn't contain two items
words.reject!{|element| element.size != 2}
hth,
Mark
>
> If I tried to print second element from array (it should be word2),I
> have got nil.
>
> Thank you in advance
>
>