3

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]]
2
  • +0 for not bothering to check that the code you posted gives the same error message as you stated in the question. Commented May 17, 2012 at 0:13
  • fixed. Didn't think it was such big deal Commented May 17, 2012 at 14:40

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Should also be noted that using global variables (those that begin with $) is frowned upon.
Thanks! good catch, didn't know it :) pulls some hairs off I realized my main mistake was on the regex. The original code had more complex regex, and I missed it.
Without seeing a stack trace, I'm not going to worry about the actual error.
Its actually s' not _'. I put it there so it wouldn't be specific to this problem
1

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

1 Comment

Thanks Ron. I got the answer above though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.