Replacing a character in a string

So I want to be able to take a string with underscores in it (’_’) and
replace those with spaces…can somebody please tell me why this isn’t
working:

if cal_name.include? ‘
cal_name.sub!(’
’, ’ ')
end

I can’t see why this isn’t doing the trick…but maybe I’m doing
something wrong. If anyone could give me any idea of what’s wrong…or
even a different approach, that would be great!

Thanks

Umm, what exactly makes you think it isn’t working?
It is working, but for sub, not gsub.

sub replaces the first, gsub replaces all

Also, you don’t need to do this in an if statement. If the underscore
isn’t present, sub and gsub won’t complain.

#Probably what you want.
cal_name.gsub!(’_’,’ ')

Good luck,
–Kyle

On Jun 10, 2008, at 1:19 PM, Amanda … wrote:

even a different approach, that would be great!
Well, that code should work to replace the first underscore in a
String. If you want all of them, use gsub!() instead. You can also
drop the if statement, as it has no effect here.

I would use tr() for this, if you want to replace them all:

cal_name.tr("_", " ")

James Edward G. II

On 10.06.2008 20:19, Amanda … wrote:

even a different approach, that would be great!
Works for me - but if you use sub instead of gsub only the first
occurrence is replaced.

irb(main):001:0> s=“a_b”
=> “a_b”
irb(main):002:0> s.include? ""
=> true
irb(main):003:0> s.sub '
’, ’ ’
=> “a b”
irb(main):004:0> s=“a_b_c”
=> “a_b_c”
irb(main):005:0> s.sub ‘_’, ’ ’
=> “a b_c”
irb(main):006:0>

I’d do just this:

irb(main):006:0> s.gsub ‘_’, ’ ’
=> “a b c”

Or, in your case use gsub! - but without the check (unnecessary
overhead).

Kind regards

robert

Hey, I’m a newbie, but here’s one solution:

cal_name = “testing_this_out”

match = ‘_’
while(cal_name.include?(match))
cal_name.sub!(match, ’ ')
end

puts cal_name #=> testing this out

Your solution prints “testing this_out” with only the first underscore
substituted. String#sub only replaces the first occurence of the
pattern.

Refer to class String - RDoc Documentation for
some information on the String object’s methods.

Hope this helps!! =D

After reviewing everyone elses comments, I’ll have to redo my naive
solution:

cal_name = “testing_this_out”

cal_name.gsub!(’_’, ’ ')

puts cal_name

haha my mistake…i thought sub! changed all of the occurrences of ‘_’.
Thanks for the clarification all, it’s working now :slight_smile:

James G. wrote:

cal_name.tr("_", " ")

Coming recently from Perl, this looks very familiar to me. In Perl
syntax:

$cal_name =~ tr/_/ /;

In Ruby you’ll need cal_name.tr!("", " “) if you want to make the
substitution permanent. (I keep getting caught by this!) Or
cal_name.tr_s!(”
", " ") if you want to squeeze multiple space
characters down to a single space too.