我正在尝试编写一个方法,它接受一个字符串和一个散列,并根据散列键和值“编码”字符串。基于散列值转换字符串
def encode(str,encoding)
end
str = "12#3"
encoding = {"1" => "one", "2"=> "two", "3"=> "three"}
我期待的输出为"one two three"
不在哈希键被替换为空字符串在字符串中的任何字符。
现在我的代码如下所示:
def encode(str, encoding)
output = ""
str.each_char do |ch|
if encoding.has_key?(ch)
output += encoding[ch]
else
output += ""
end
end
return output
end
任何帮助表示赞赏
WOW ....从来没有这个作品...我有一个错字我的代码 –