【问题标题】:pig latin ruby translator issue猪拉丁红宝石翻译问题
【发布时间】:2014-04-16 15:35:25
【问题描述】:

您好,我的猪拉丁代码有问题,我正在处理来自 Ruby 的 Learn First 文件,我基本上想做的是以下内容,如果一个单词以元音开头=> apple 将变为 appleay ,如果以辅音开头=>banana => ananabay,如果以两个辅音开头=>cherry => errychay,也可以翻译两个词=>eat pie 会变成eatay iepay 以此类推,这里是我的代码:

def translate(string)

    vowels = [ "a" , "e" , "i" , "o" , "u"]
    alphabet = ("a" .. "z").to_a
    consonants = alphabet - vowels

    string_split = string.split

    string_split.map! do |w|
        if vowels.include?(w[0])
            w + 'ay'
        elsif consonants.include?(w[0]) &&

            consonants.include?(w[1])

            w [2..-1] + w [0..1]+ 'ay'

        elsif w [0..1] == "qu"

            w[2..-1] + "quay"

        elsif w[0..2] == "thr"

            w [3..-1]+"thray"

        elsif w[0..2]== "sch"

            w[3..-1]+"schay"

        elsif consonants.include?(w[0])

            w[ 1..-1] + w[0..0] + 'ay'
        else
                w

        end
    end

    return string_split.join(" ")

end

【问题讨论】:

  • @mike 当我尝试使用 ruby​​ 提示符运行它时,它说“翻译一个以元音开头的单词(FAILED -1)
  • 首先,启动 irbload 包含此代码的文件。然后,尝试测试它并查看它是否返回所需的输出。例如,您可以在irb 中输入translate("apple"),看看它会返回什么。
  • 请提供完整的堆栈跟踪和错误消息。
  • 我把它卡在了pry得到了translate("allo"); NoMethodError: undefined method 'elseif' for main:Object OP,最好看到错误信息,然后你可以立即看到它不知道elseif,然后你可以立即看到什么问题.

标签: ruby


【解决方案1】:

很简单,是elsif 不是elseif

def translate(string)

  vowels = [ "a" , "e" , "i" , "o" , "u"]
  alphabet = ("a" .. "z").to_a
  consonants = alphabet - vowels

  string_split = string.split

  string_split.map! do |w|
    if vowels.include?(w[0])
      w + 'ay'
    elsif consonants.include?(w[0]) &&

        consonants.include?(w[1])

      w [2..-1] + w [0..1]+ 'ay'

    elsif w [0..1] == "qu"

      w[2..-1] + "quay"

    elsif w[0..2] == "thr"

      w [3..-1]+"thray"

    elsif w[0..2]== "sch"

      w[3..-1]+"schay"

    else consonants.include?(w[0])

      w[ 1..-1] + w[0..0] + 'ay'


    end
  end

  return string_split.join(" ")

end

【讨论】:

  • 谢谢我现在用 elsifs 修复了这一切,并运行了程序,它一直运行到我需要翻译三个辅音的地步,它说预期:“eethray”得到:“reethay”,但是我的代码中有一行: elsif w[0..2] == "thr" w [3..-1]+"thray",不知道为什么它不起作用
  • @user3541885 是的,但是您在三个辅音条件之上有 2 个辅音条件,因此永远不会被执行。 ruby 按顺序尝试每个条件。
  • 哦,我明白了,有没有办法可以重写代码,以便可以采用任何条件?抱歉,我是 ruby​​ 和一般编码的新手
  • 只需将两个辅音线放在底部,并考虑在每种情况下首先要敲什么。
  • 要了解解决此问题的更有效方法,请阅读 regular expressions 并查看 gsub 哦,如果此答案有帮助,请接受并点赞。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多