ruby - How do I iterate through an array and change characters efficiently? -
i have method in work ruby assignment need change vowels , consonants in name put in user, next successive vowel/consonant, ( = e, e = i, etc.) , same process consonants ( b = c, d = f, etc.). did 'easy' way, need change instead, iterating through array , changing vowels/consonants way.
i new iteration having trouble this.
here original method:
puts "what full name?" full_name = gets.chomp def vowelreplace(full_name) vowels = 'aeiou' replacements = 'eioua' full_name.tr(vowels, replacements) end name_next_vowel = vowelreplace(full_name) p name_next_vowel def consonantreplace(name_next_vowel) consonants = 'bcdfghjklmnpqrstvwxyz' replacements = 'cdfghjklmnpqrstvwxyzb' name_next_vowel.tr(consonants, replacements) end new_spyname = consonantreplace(name_next_vowel) p new_spyname
here's i've started working change below using array , block method. there easier less lengthy way of doing this? there .next way of doing this, or in general, more efficient way?
puts "what first name?" first_name = gets.chomp arr = first_name.split("") p arr arr.map! { |element| if(element == "a") "e" elsif(element == "e") "i" elsif(element == "i") "o" elsif(element == "o") "u" elsif(element == "u") "a" else element end } p arr new_arr = arr new_arr.map! { |element| if(element == "b") "c" elsif(element == "c") "d" elsif(element == "d") "f" elsif(element == "f") "g" elsif(element == "g") "h" elsif(element == "h") "j" elsif(element == "j") "k" elsif(element == "k") "l" elsif(element == "l") "m" elsif(element == "m") "n" elsif(element == "n") "p" elsif(element == "p") "q" elsif(element == "q") "r" elsif(element == "r") "s" elsif(element == "s") "t" elsif(element == "t") "v" elsif(element == "v") "w" elsif(element == "w") "x" elsif(element == "x") "y" elsif(element == "y") "z" elsif(element == "z") "b" else element end } p new_arr arr.join("")
i tr
approach, if want similar next
, array#rotate
option; here's example:
def letter_swap(full_name) vowels = %w(a e o u) consonants = %w(b c d f g h j k l m n p q r s t v w x y z) full_name.each_char.with_object("") |char, new_name| if vowels.include?(char) new_name << vowels.rotate(vowels.index(char) + 1).first elsif consonants.include?(char) new_name << consonants.rotate(consonants.index(char) + 1).first else new_name << char end end end
of course dry code, @ expense of readability (imo); example:
def letter_swap(full_name) letters = [%w(a e o u), %w(b c d f g h j k l m n p q r s t v w x y z)] full_name.each_char.with_object("") |char, new_name| group = letters.find { |group| group.include?(char) } new_name << (group.nil? ? char : group.rotate(group.index(char) + 1).first) end end
Comments
Post a Comment