Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm still new at ruby. My array is not being seen for some reason. I tested my code logic in irb, and it seemed to work alright, but when I have it in if statements, it breaks with the error in the title.

$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

An 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 end up with an array s, like such?

[[m1,p1,p2,p3,p4], [m2,p1,p2,p3,p4,p5], [m3,p1], [m4], [m5]]
like image 201
mhz Avatar asked May 30 '26 07:05

mhz


2 Answers

You've declared the array as $s, but are trying to access it as s. These are two different variables as far as Ruby is concerned. You should either declare it as s = [] or access it always as $s, e.g. $s << [$1].

EDIT: Because the comment is so popular, I'll add that Ruby global variables (i.e. those that begin with $) can lead to very-difficult-to-debug situations, and I would discourage you from using them. I'm not able to think of a situation of using a global where a cleaner solution isn't possible.

like image 67
x1a4 Avatar answered Jun 02 '26 02:06

x1a4


You should initialize a new sub-array in your main array each time you hit an m line. If you hit a p line, you append to that same index.

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
like image 34
Ron Avatar answered Jun 02 '26 00:06

Ron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!