From: Stefan Kruger Date: 2007-06-15T03:01:23+09:00 Subject: Characters and strings oddness Hi there Rubyists - I'm trying to learn the language, coming from a long background in Perl. Here's what I want to do: pick out a double-quoted string inside another string, respecting embedded, backslashed quotes: line = ' a string "properly \"quoted\" that ends" here ' quoted = '"properly \"quoted\" that ends"' If Ruby had the same regexes as Perl, I'd say something like line.gsub!(/^\s*(\".*?(?0 && (line[i, 1] == "\"") && (line[i-1, 1] != '\\') end end which works. However.. I'm puzzled by Ruby's way of handling strings. A string is - essentially - a set of bytes, not unlike a char[] in C. Is there really no way of defining character literals in Ruby? I was surprised to find that I couldn't say Stefan-Krugers-Computer:~ stefan$ irb irb(main):001:0> string = 'this is a string' => "this is a string" irb(main):002:0> string[0] == 't' => false whereas i *can* say irb(main):003:0> string[0, 1] == 't' => true Now, in my little loop experiment above I tried the following: delim = "\"" string = delim if line.gsub!(/^.*?(\")/, '') (0..line.length).each do |i| string << line[i] break if i>0 && (line[i, 1] == delim) && (line[i-1, 1] != '\\') end end TypeError: can't convert nil into String method << in test.rb at line 9 at top level in test.rb at line 9 at top level in test.rb at line 8 I'm at a loss to understand why that gives an error. -- Stefan Kruger