将字符串转换为数组后从字符串中删除特定项目

问题描述

所以我在下面所做的是从用户那里获取一个数字并将字母表中的字母转换为该特定数字。例如,当 str = "aby" 且 num = 3 时,输出将为 "deb"。它只适用于字母。但是会有标点符号、空格等,如果我输入“A by 3”。作为字符串,我遇到了诸如 Nomethod 错误之类的错误。(输出应为:“D eb 3。”)如何移动字母并同时保持其他字母不变?

ps:请不要为此编写新代码。我只是想解决我自己代码的问题。谢谢。

puts "Please type a number: "
num = gets.chomp.to_i  

alp = ("a".."z").to_a  

# This is the erroneous part :
str = "aby".split("")

number_conv = str.map { |a| alp.index(a) + num}

letter_conv = number_conv.map do |e|
  if e + num < 26 
    alp[e]
  else   
    e = (e + num) % 26
    alp[e - num]
  end
end

p letter_conv.join

解决方法

包装您的代码以将字符转换为函数。在切换时添加条件以忽略特殊字符。

在正文中,用空格分割你的句子,并将每个单词传递给上述函数。

def shift mystr,num
  ignore = %w{( ) ?,}  # put all the characters you want to ignore here.
  alp = ("a".."z").to_a

  str = mystr.split("")
  
  number_conv = str.map { |a| ignore.include?(a) ? a : alp.index(a) + num}

  letter_conv = number_conv.map do |e|
    if ignore.include?(e)
      e
    elsif e + num < 26
      alp[e]
    else
      e = (e + num) % 26
      alp[e - num]
    end
  end
  letter_conv.join
end

puts "Please type a number: "
num = gets.chomp.to_i
puts "Please type a string: "
str = gets.chomp
puts str.split.map {|i| shift i,num}.join(" ")