ruby - I changed my integers to strings, but #gsub only recognizes 0-9 -
i'm self-learning ruby, , 1 assignment make caesar cipher. using #gsub, i've been able change letters integers ('c' => 2), shift them, change new integers strings (2 => "2").
i've hit wall, , ruby documentation isn't helping. when try #gsub strings letters ("2" => 'c') recognizes 0-9. after concatenation of numbers ("12" => 'bc' instead of => 'l').
why ruby this, , how can fix it?
thanks guys.
code: (i know it's sloppy beginner's code; try edit after passes)
def convert_to_integer puts "what encode?" words = gets.chomp words = words.split("") words.map { |words| words.gsub!(/[a-z]/, 'a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'e' => 4, 'f' => 5, 'g' => 6, 'h' => 7, 'i' => 8, 'j' => 9, 'k' => 10, 'l' => 11, 'm' => 12, 'n' => 13, 'o' => 14, 'p' => 15, 'q' => 16, 'r' => 17, 's' => 18, 't' => 19, 'u' => 20, 'v' => 21, 'w' => 22, 'x' => 23, 'y' => 24, 'z' => 25) } integer = words.map! { |letter| letter.to_i } return integer end def shift_left(integer, number = 0) puts "how many letters (to left) shift it?" number = gets.to_i integer.map! { |n| n - number } return integer end def convert_to_letter(integer) integer.map! { |integer| integer.to_s } integer.map! { |n| n.gsub(/[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]/, '0' => 'a', '1' => 'b', '2' => 'c', '3' => 'd', '4' => 'e', '5' => 'f', '6' => 'g', '7' => 'h', '8' => 'i', '9' => 'j', '10' => 'k', '11' => 'l', '12' => 'm', '13' => 'n', '14' => 'o', '15' => 'p', '16' => 'q', '17' => 'r', '18' => 's', '19' => 't', '20' => 'u', '21' => 'v', '22' => 'w', '23' => 'x', '24' => 'y', '25' => 'z') } print integer end convert_to_letter(shift_left(convert_to_integer))
you don't need gsub
there. gsub
used replace parts of bigger string. want replace whole thing.
this should trick:
def convert_to_letter(integers) replacements = {0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h', 8 => 'i', 9 => 'j', 10 => 'k', 11 => 'l', 12 => 'm', 13 => 'n', 14 => 'o', 15 => 'p', 16 => 'q', 17 => 'r', 18 => 's', 19 => 't', 20 => 'u', 21 => 'v', 22 => 'w', 23 => 'x', 24 => 'y', 25 => 'z' } integers.map{|x| replacements[x]}.join end
also, careful destructive operations (map!
here). may run undesired side-effects (for example, arrays change when think shouldn't).
Comments
Post a Comment