如何将零变为" "在数组中

时间:2016-10-08 19:28:49

标签: ruby

#ask user for string input
puts "Enter Text"
# text user has entered
text = "Test text"
#put text into a array - "split" by just words and spaces
words = text.downcase.split('')
#array of letters a to z in array 
a_z = ('a'..'z').to_a 

#idealy - take each letter in text string and match them to a_z's index from 0-25 
#space values in text are replaced in array with " " instead of nil

words.map { |x| a_z.index(x) }

我正在尝试使用文本,拆分文本,将文本转换为基于a到z索引的数字...移动该数字并重新组合并转回文本...

我现在遇到的问题是我的文本数组中的空格显示为nil,因为它们在a-z索引中没有nil的数值。

如何用"替换nil? "所以我的数组可以看起来像这样:

#=> [1,2," "]

而不是:

#=> [1,2,nil]

1 个答案:

答案 0 :(得分:0)

<强>代码

def shift_and_remove(str, shift)
  h = make_hash 'a'..'z', shift
  h.default_proc = ->(h,k) {' '}
  str.gsub(/./,h)
end

def make_hash(r, shift)
  base = r.first.ord
  r.each_with_object({}) { |c,h| h[c] = (base + (c.ord-base+shift) % 26).chr }
end    

<强>实施例

str = "Now is the time for 007 to appear!"
shift_and_remove(str, 0)  #=> " ow is the time for     to appear " 
shift_and_remove(str, 1)  #=> " px jt uif ujnf gps     up bqqfbs " 
shift_and_remove(str, 4)  #=> " sa mw xli xmqi jsv     xs ettiev " 
shift_and_remove(str, -1) #=> " nv hr sgd shld enq     sn zoodzq " 
shift_and_remove(str, -2) #=> " mu gq rfc rgkc dmp     rm ynncyp "

请注意,在所有情况下,“N”已被转换为空格,“Now”的“w”在第三个示例中已转换为“a”,“come”的“a”已转换为“z” “和”y“分别在最后两个例子中。

<强>解释

shift #=> 2时,哈希值如下:

h[c] = ('a'.ord + (c.ord-'a'.ord+shift) % 26).chr }
  #=> {"a"=>"c", "b"=>"d", "c"=>"e", "d"=>"f", "e"=>"g", "f"=>"h", "g"=>"i",
  #    "h"=>"j", "i"=>"k", "j"=>"l", "k"=>"m", "l"=>"n", "m"=>"o", "n"=>"p",
  #    "o"=>"q", "p"=>"r", "q"=>"s", "r"=>"t", "s"=>"u", "t"=>"v", "u"=>"w",
  #    "v"=>"x", "w"=>"y", "x"=>"z", "y"=>"a", "z"=>"b"} 

所有字母“a”到“x”都映射到下一个字母,而“y”和“z”分别映射到“a”和“b”。同样,当shift #=> -1时,“a”映射到“z”,所有其他字母映射到前面的字母。

这使用String#gsub的形式,它使用哈希来确定字符串中每个字符的替换(/./)。方法Hash#default_proc=创建一个proc,当哈希h[k]没有键h时,它会给出k的值,即空格。

大写字母

如果存在任何大写字母要转换为大写字母(而不是转换为空格),则只需要稍作修改。

def shift_and_remove(str, shift)
  h = make_hash('a'..'z', shift).merge make_hash('A'..'Z', shift)
  h.default_proc = ->(h,k) {' '}
  str.gsub(/./,h)
end

shift_and_remove(str, 0)  #=> "Now is the time for     to appear " 
shift_and_remove(str, 1)  #=> "Opx jt uif ujnf gps     up bqqfbs " 
shift_and_remove(str, 4)  #=> "Rsa mw xli xmqi jsv     xs ettiev " 
shift_and_remove(str, -1) #=> "Mnv hr sgd shld enq     sn zoodzq " 
shift_and_remove(str, -2) #=> "Lmu gq rfc rgkc dmp     rm ynncyp "