0

I am trying to regex a character from a string that was assigned from an element of a scan result. I am trying to use match and it is complaining that the variable is an array. I am confused as to why "trash" is being seen as an array.

test = 'class="date">B=oddTu Q='
array = test.scan(/([A-Z])=/)
puts array
trash = array.last
trash.to_s
puts trash
if /Q/.match(trash)
  puts $1
end

And this is the results I'm seeing

C:\Ruby>scratch.rb
class="date">B=oddTu Q=
B
Q
Q
C:/Ruby/scratch.rb:14:in match: can't convert Array to String (TypeError)
        from C:/Ruby/scratch.rb:14:in `<main>'

EDIT: scan returns an array of array, so by doing trash = array.last, trash then gets taken down one level to 1 array. Doing trash = trash[0] then takes it down to a string.

1
  • 2
    array is an array of arrays, so trash is actually an array. Use p trash to dump the variable and you'll see Commented Dec 13, 2012 at 12:57

2 Answers 2

2

The problem is that trash is an array (of single element "Q"). You see it when you serialize.

See those two lines taken from my irb:

test.scan(/([A-Z])=/)
=> [["B"], ["Q"]]

The scan is returning array of arrays - for each match a value for each group.

You can not do matching on an array.

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

Comments

1

As Boris points out, you're getting an array of arrays. It's because you have a group in your regex (a parenthesised expression). If you had several such groups, they would each correspond to an element in the returned arrays:

test.scan(/([A-Z])(=)/)
# => [["B", "="], ["Q", "="]]

In your case there's a few ways around this. You could simply flatten the array:

test.scan(/([A-Z])=/).flatten
# => ["B", "Q"]

or you could use a positive lookahead instead of grouping the bit you're interested in:

test.scan(/[A-Z](?==)/)
# => ["B", "Q"]

Unfortunately, since the bit you're not interested in is the = sign, it looks a bit weird with the lookahead syntax (?=pattern), so the flatten option might be clearer.

Comments

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.