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

arrays, dynamic, ruby

Solution

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.

Problem

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]] ```

Original source