Forum: Ruby Swapping characters in a string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ee04bc0ca6dcdad4a7e8a8e1d4efb5d0?d=identicon&s=25 Michael W. Ryder (Guest)
on 2007-04-30 04:06
(Received via mailing list)
Is there any way in Ruby, short of stepping through a string character
by character, to swap two characters?  For example, if I want to replace
all of the commas with periods and periods with commas.
B8cfd5ec0f88bf5b5f2eedda7d1a0746?d=identicon&s=25 unknown (Guest)
on 2007-04-30 04:09
(Received via mailing list)
In message <F5cZh.387091$5j1.283606@bgtnsc04-news.ops.worldnet.att.net>,
"Michael W. Ryder" wri
tes:
>Is there any way in Ruby, short of stepping through a string character
>by character, to swap two characters?  For example, if I want to replace
>all of the commas with periods and periods with commas.

Shouldn't String#tr do it?

foo.tr!(',.', '.,')

-s
Ee04bc0ca6dcdad4a7e8a8e1d4efb5d0?d=identicon&s=25 Michael W. Ryder (Guest)
on 2007-04-30 05:01
(Received via mailing list)
Peter Seebach wrote:
> -s
>
Yes that works fine.  For some reason when I saw that method I didn't
think it could swap characters.  That's what I get for not experimenting
first.  Thanks for the help.
This topic is locked and can not be replied to.