【问题标题】:Can you append to specific elements in an array based on if statement conditions?您可以根据 if 语句条件附加到数组中的特定元素吗?
【发布时间】:2013-08-29 05:14:04
【问题描述】:

我是一名开发人员训练营的学生,我的一个项目遇到了问题。我们正在使用 Ruby 编写 Pig Latin 页面。我让它通过了测试,直到它需要接受多个单词:

def pig_latina(word)
  # univeral variables
vowels = ['a','e','i','o','u']
user_output = ""
  # adds 'way' if the word starts with a vowel
  if vowels.include?(word[0]) 
     user_output = word + 'way'     
  # moves the first consonants at the beginning of a word before a vowel to the end  
  else 
    word.split("").each_with_index do |letter, index|

      if vowels.include?(letter)
        user_output = word[index..-1] + word[0..index-1] + 'ay'
      break
      end
    end 
  end   
  # takes words that start with 'qu' and moves it to the back of the bus and adds 'ay'
  if word[0,2] == 'qu'
  user_output = word[2..-1] + 'quay'
  end
  # takes words that contain 'qu' and moves it to the back of the bus and adds 'ay'
  if word[1,2] == 'qu'
  user_output = word[3..-1] + word[0] + 'quay'
  end
  # prints result
  user_output
end

我不知道该怎么做。这不是家庭作业或任何东西。我试过了

  words = phrase.split(" ")
    words.each do |word|
    if vowels.include?(word[0])
      word + 'way'

但我认为else 声明把这一切搞砸了。任何见解将不胜感激!谢谢!!

【问题讨论】:

  • 您的代码非常难以理解。而是告诉我们您想要的示例字符串和预期输出..
  • 您的问题是什么?我在底部代码部分没有看到 else 语句。
  • 您的代码有点搞混了。您将短语拆分为单词、转换每个单词然后重新加入的整体逻辑是正确的(您可以使用phrase.split(" ").collect { |w| pig_latina(w) }.join(" "))。但是您处理单词的详细代码几乎是在尝试处理短语,但并不完全是。您可能需要在每个 qu 案例之前有一个 else,因为它们与前两个案例互斥。其余的看起来有点乱,但我认为是合理的。
  • 您应该尝试使用 pry 进行调试。你可以做require "pry",然后在你想进入代码的任何地方输入一行binding.pry。这就是我解决这类问题的方法。

标签: ruby arrays


【解决方案1】:
def pig_latina(word)
  prefix = word[0, %w(a e i o u).map{|vowel| "#{word}aeiou".index(vowel)}.min]
  prefix = 'qu' if word[0, 2] == 'qu'
  prefix.length == 0 ? "#{word}way" : "#{word[prefix.length..-1]}#{prefix}ay"
end

phrase = "The dog jumped over the quail"
translated = phrase.scan(/\w+/).map{|word| pig_latina(word)}.join(" ").capitalize

puts translated  # => "Ethay ogday umpedjay overway ethay ailquay"

【讨论】:

  • 谢谢!这有助于正确看待事情。
【解决方案2】:

我会将您的逻辑分为两种不同的方法,一种用于转换单个单词的方法(有点像您所拥有的),另一种用于获取句子、拆分单词并在每个单词上调用您以前的方法的方法。它可能看起来像这样:

def pig(words)
  phrase = words.split(" ")
  phrase.map{|word| pig_latina(word)}.join(" ")
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多