notthehoff
notthehoff

Reputation: 1242

Replace different sets of characters with different sets of numbers using regex

I am trying to replace characters in a string with a shift in the ord by some number. I am thinking the best way to do this is with regex, but running into some problems.

This is the flawed code I do have

def cipher(coded_message)
  coded_message=coded_message.downcase.split("")
  new_message=[]
  coded_message.each do |x|
    x=x.gsub(/[a-d][e-z]/, '\1x.ord+22\2x.ord-4')
    new_message<<x
  end
  p new_message.join
end

I know that my problem is with the regex and probably the replacement text, but not sure where to go on this one. Any help would be appreciated.

Upvotes: 0

Views: 90

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

Not much point coding a message if you can't decode it:

@code_key = 123.times.with_object({}) do |i,h|
  c = i.chr
  h[c] =
    case c
    when /[a-dA-D]/ 
      (i+22).chr
    when /[e-zE-Z]/
      (i-4).chr
    else
      c
    end
end

@decode_key = @code_key.invert

def code(message)
  @code_key.values_at(*message.chars).join
end

def decode(message)
  @decode_key.values_at(*message.chars).join
end

message = "Is 42 an important number?"
coded_message   = code(message)         # => "Eo 42 wj eilknpwjp jqixan?"
decoded_message = decode(coded_message) # => "Is 42 an important number?"

Upvotes: 1

MrPizzaFace
MrPizzaFace

Reputation: 8086

Ok so I took a different approach to solving your problem. Here is a solution which doesn't involve a regex, and is very flexible.

def cipher(coded_message)
  new_message=[]
  coded_message.downcase.each_char do |x|
    case x
    when ("a".."d")
      new_message << (x.ord+22).chr
    when ("e".."z")
      new_message << (x.ord-4).chr
    end
  end
  new_message.join
end

cipher("Code this string")
 #=> "ykzapdeoopnejc" 

Upvotes: 3

Related Questions