Puzzled?

Hi,
I have a question...

Why the below snippet,

["foo","bar","baz"].each do |s|
    m = /^ba(.*?)$/.match(s)
    puts m[0]
end

gives the following error?

test.rb:8: undefined method `[]' for nil:NilClass (NoMethodError)

Regards,
Volkan

Regexp#match returns nil if it doesn't match anything. On the first run through your each statement, s is "foo", which doesn't match against your regex. That means m is nil, and so you get an error when trying to grab m[0].

···

On 1/07/2006, at 12:58 PM, Volkan Civelek wrote:

Hi,
I have a question...

Why the below snippet,

["foo","bar","baz"].each do |s|
    m = /^ba(.*?)$/.match(s)
    puts m[0]
end

gives the following error?

test.rb:8: undefined method `' for nil:NilClass (NoMethodError)

Regards,
Volkan