views:

307

answers:

3

I want to find the successor of each element in my encoded string. For example K->M A->C etc.

string.each_char do |ch| 
    dummy_string<< ch.succ.succ
end

However this method translates y->aa.

Is there a method in Ruby that is like maketrans() in Python?

+7  A: 

You seem to be looking for String#tr. Use like this: some_string.tr('a-zA-Z', 'c-zabC-ZAB')

Pesto
what is there ab after z? How do I interpret that?
kunjaan
It basically means that the letters a-z will be replaced by the letters c-z, a, then b. Since the range c-z is two characters shorter, apparently you can specify extra characters.Still, that seems like very bizarre syntax. Neat though.
Burke
A: 

I don't know of one offhand, but I think the Ruby way would probably involve passing a block to a regexp function. Here's a dumb one that only works for upper-case letters:

"ABCYZ".gsub(/\w/) { |a| a=="Z" ? "A" : a.succ }
=> "BCDZA"

Edit: meh, never mind, listen to Pesto, he sounds smart.

Ken
There is no so-called Ruby way. You can walk your way in Ruby -- which may be String#gsub or String#tr, or something else. Please note that String#tr is much faster than String#gsub with a block.
pts
They don't call it the "Ruby way", but there are certainly things you can do in Ruby code that will get you laughed (or insulted) out of the room at Ruby meetings. I've even gotten (physically) hit at Ruby meetings for my beliefs, so I don't agree that "you can walk your way in Ruby": Ruby programmers are as protective of their culture as any other group.
Ken
+1  A: 
def successor(s)
    s.tr('a-zA-Z','c-zabC-ZAB')
end

successor("Chris Doggett") #"Ejtku Fqiigvv"
Chris Doggett