-2

我正在解析简单的字符串输入,例如:“Hello world!:-)”并将它们转换为一个数组,该数组拆分单词并可能进行一些修改。我已经生成了以下有效的代码,但它似乎不是非常 Ruby 惯用的。我该如何改进它?

$mapping = Hash[
  "X" => "CODE_X",
  "Y" => "CODE_Y",
  "Z" => "CODE_Z",
]

def translate(input)
  result = []
  tmp = ""
  input.each_char do |c|
    if $mapping.has_key?(c)
      if result != ""
        result << "normal " + tmp
        tmp = ""
      end
      result << "special " + $mapping[c]
    else
      tmp += c
    end
  end
  if tmp != ""
    result << "normal " + tmp
  end
  return result
end

它似乎包含不必要的许多行,使其难以阅读。它有什么作用,也许一个例子有帮助:

translate("HelloXworldYZ") =>
["normal Hello", "special CODE_X", "normal world", "special CODE_Y", "special CODE_Z"]

或者用英语:按字符解析字符串并再次连接字符。将它们作为“普通”+字符串添加到结果数组中,直到(1)没有更多字符或(2)有特殊字符(映射),他们将字符串添加到数组中并将特殊字符添加为“特殊” + 映射并继续字符串的其余部分。

4

3 回答 3

2

怎么样

$mapping = { 'X' => 'CODE_X', 'Y' => 'CODE_Y', 'Z' => 'CODE_Z' }

def translate(input)
  input.
    split(/([#{$mapping.keys.map(&Regexp.method(:escape)).join}])/).
    each_slice(2).
    map {|normal, special| [unless normal.empty? then "normal #{normal}" end, "special #{$mapping[special]}"] }.
    map(&:compact).
    flatten
end

translate("HelloXworldYZ")
# => ["normal Hello", "special CODE_X", "normal world", "special CODE_Y", "special CODE_Z"]

请注意,您的简单英文描述和您的测试用例不匹配。根据您简单的英文描述,结果应该是["normal Hello", "special CODE_X", "normal world", "special CODE_Y", "normal", "special CODE_Z"]. 在这种情况下,它甚至更简单:

$mapping = { 'X' => 'CODE_X', 'Y' => 'CODE_Y', 'Z' => 'CODE_Z' }

def translate(input)
  input.
    split(/([#{$mapping.keys.map(&Regexp.method(:escape)).join}])/).
    each_slice(2).
    map {|normal, special| [['normal', unless normal.empty? then normal end].compact.join(' '), "special #{$mapping[special]}"] }.
    flatten
end

translate("HelloXworldYZ")
# => ["normal Hello", "special CODE_X", "normal world", "special CODE_Y", "normal", "special CODE_Z"]

但是strscan图书馆可能是更好的选择。

于 2013-01-08T03:35:08.877 回答
2
def translate(input,map)
  input.split(/([#{Regexp.escape map.keys.join}])/).map do |part|
    map.key?(part) ? "special #{map[part]}" : "normal #{part}" unless part.empty?
  end.compact
end

p translate( "HelloXworldYZ", 'X'=>'CODE_X', 'Y'=>'CODE_Y', 'Z'=>'CODE_Z' )
#=> ["normal Hello", "special CODE_X", "normal world", "special CODE_Y", "special CODE_Z"]
于 2013-01-08T03:38:59.303 回答
0
$mapping = Hash[
  "x" => "CODE_X",
  "y" => "CODE_Y",
  "z" => "CODE_Z",
]

def translate(input)
  $mapping.keys.each { |char| input.gsub!(char, "___#{char}___") } 
  array = input.split(/(___.___)/)
  result = []

  array.each do |word|
    if word.match /___.___/
      result << "special #{$mapping[word[3]]}"
    else
      result << "normal #{word}" unless word.empty?
    end
  end
  result
end

translate("Helloxworldyz")
#=> ["normal Hello", "special CODE_X", "normal world", "special CODE_Y", "special CODE_Z"]
于 2013-01-08T03:46:39.500 回答