Ruby Dynamic Array: undefined local variable or `s' method for main: Object (NameError)

I'm still new to ruby. For some reason, my array is not visible. I tested my code logic in irb and it seems to work fine, but when I have it in if statements, it breaks with an error in the header.

$s = []

i = 0

File.open("test.log").each do | l |
    if l =~ /(m.)/
        s << [$1]
        i=i+1
    end

    if l =~ /(p.)/
        s[i-1] << $1
    end

end

s.each do |g|
    p g
end

Example test.log:

aaaaaaaaaaaaaaaaaa
m1
ggg
p1
p2
p3
p4
oooooooooooooo
m2
p1
p2
p3
p4
p5
gggggggggggggg
m3
p1
kkkkkkkkkkkk
m4
m5
llllllllllllll

How can I get an array s, like this?

[[m1,p1,p2,p3,p4], [m2,p1,p2,p3,p4,p5], [m3,p1], [m4], [m5]]
+3
source share
2 answers

You declared the array as $s, but you are trying to access it as s. These are two different variables with regard to Ruby. You must either declare it as s = [], or always get it as $s, for example. $s << [$1].

EDIT: , , Ruby (.. , $), , . , .

+5

, m. p, .

index = -1;
array = []
File.open("test.log").each do |line|
  if line =~ /m./
    index = index + 1
    array[index] = []
    array[index] << line
  end

  if line =~ /p./
    array[index] << line
  end
end
+1

All Articles