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.
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:
In your case there’s a few ways around this. You could simply
flattenthe array:or you could use a positive lookahead instead of grouping the bit you’re interested in:
Unfortunately, since the bit you’re not interested in is the
=sign, it looks a bit weird with the lookahead syntax(?=pattern), so theflattenoption might be clearer.