Hi all,
I ran into a little problem with String#tr today. I wanted to do something like:
str = 'kame^hame^ha^'
str.tr('^','-')
But I got back an error about having a nil character class ([^]).
According to the docs: "Both strings may use the c1—c2 notation to
denote ranges of characters, and from_str may start with a ^, which
denotes all characters except those listed."
So it's trying to interpret the first argument as some sort of a
single character regex, even though it's in a string. Bummer. How then
can I replace a carat character in my string?
str.tr('\^','-') doesn't seem to work either.
Is there any way of doing this? I know that I can just use gsub
instead and go on with my life (I have actually), but this is
bothering me for some reason.
Thanks!
-Pawel
irb(main):003:0> str = 'kame^hame^ha^'
=> "kame^hame^ha^"
irb(main):004:0> str.tr '^', '-'
=> "kame-hame-ha-"
···
On 6/24/06, Pawel Szymczykowski <makenai@gmail.com> wrote:
Hi all,
I ran into a little problem with String#tr today. I wanted to do something like:
str = 'kame^hame^ha^'
str.tr('^','-')
But I got back an error about having a nil character class ([^]).
According to the docs: "Both strings may use the c1—c2 notation to
denote ranges of characters, and from_str may start with a ^, which
denotes all characters except those listed."
So it's trying to interpret the first argument as some sort of a
single character regex, even though it's in a string. Bummer. How then
can I replace a carat character in my string?
str.tr('\^','-') doesn't seem to work either.
Is there any way of doing this? I know that I can just use gsub
instead and go on with my life (I have actually), but this is
bothering me for some reason.
Thanks!
-Pawel
--
Mark Van Holstyn
mvette13@gmail.com
http://lotswholetime.com
Oops - thanks for the reality check, Mark.
I just realized that the exception occurs in jcode, not in the core:
irb(main):001:0> str = 'kame^hame^ha^'
=> "kame^hame^ha^"
irb(main):002:0> str.tr '^','-'
=> "kame-hame-ha-"
irb(main):003:0> require 'jcode'
=> true
irb(main):004:0> str.tr '^','-'
RegexpError: invalid regular expression; empty character class: /[^]/
from /usr/local/lib/ruby/1.8/jcode.rb:137:in `tr!'
from /usr/local/lib/ruby/1.8/jcode.rb:148:in `tr'
from (irb):4
irb(main):005:0>
That's weird I guess, but not as surprising as if was in the core
String behavior. I can live with this. Sorry for the false alarm -
it's been a long night!
-Pawel
···
On 6/23/06, Mark Van Holstyn <mvette13@gmail.com> wrote:
irb(main):003:0> str = 'kame^hame^ha^'
=> "kame^hame^ha^"
irb(main):004:0> str.tr '^', '-'
=> "kame-hame-ha-"