Problems with String#gsub!

I have here a program to help me do crossword puzzles. Yesturday, I
added the (c) and (v) symbols to match consonants and vowels
respectivly. The problem is that they do not seem to work the way I
intend them to. Here’s the program:

#!/usr/bin/env ruby

wordList = open('/home/vince/fr_dict.txt', 'r').read.split('\n')
repl = {
    '_'   => '[a-ü]',
    '(v)' => '[aâàéeèêëiîïoôöuûùüy]', 
    '(c)' => '[bcdfghjklmnpqrstvwxyz]',
    '(e)' => '[éeèêë]'
}    

while true
  print '> '
  reg = gets.chomp
  repl.each_key { |token|
    reg.gsub!(token, repl[token])
  }
  reg = '^' << reg << '$'
  puts reg
  for word in wordList
    puts word if word =~ reg
  end
end

And here’s a sample session where it does not do what I expect it to
(and gives wrong results):

[quote]
[vince@vincent: ~/prog/ruby]% ./crosswords.rb

(c)(v)(v)
^([bcdfghjklmnpqrst[aâàéeèêëiîïoôöuûùüy]wxyz])([aâàéeèêëiîïoôöuûùüy])([aâàéeèêëiîïoôöuûùüy])$

[/code]

I would’ve expected my regular expression to be:
[1][aâàéeèêëiîïoôöuûùüy][aâàéeèêëiîïoôöuûùüy]$

Why did it keep the parenthesis? Why did it replace the v with the
complet vowel set?

Thanks for you help,

Vince

···

Vincent Foley-Bourgon
Email: vinfoley@iquebec.com
Homepage: http://darkhost.mine.nu:81


  1. bcdfghjklmnpqrstvwxyz ↩︎

Try
reg.gsub!(Regexp.new(Regexp.escape(token)), repl[token])
or
reg.gsub!(/#{Regexp.escape(token)}/, repl[token])

W/o escape, you get /(c)/ for “(c)” and it means grouped one letter c.

···

At Tue, 24 Sep 2002 02:18:07 +0900, Vincent Foley wrote:

I have here a program to help me do crossword puzzles. Yesturday, I
added the (c) and (v) symbols to match consonants and vowels
respectivly. The problem is that they do not seem to work the way I
intend them to. Here’s the program:

[code]
#!/usr/bin/env ruby

wordList = open(‘/home/vince/fr_dict.txt’, ‘r’).read.split(‘\n’)
repl = {
‘_’ => ‘[a-ü]’,
‘(v)’ => ‘[aâàéeèêëiîïoôöuûùüy]’,
‘(c)’ => ‘[bcdfghjklmnpqrstvwxyz]’,
‘(e)’ => ‘[éeèêë]’
}

while true
print '> ’
reg = gets.chomp
repl.each_key { |token|
reg.gsub!(token, repl[token])