"b":String (NoMethodError) Ruby 的未定义方法“shift”

Undefined method `shift' for "b":String (NoMethodError) Ruby

我在尝试 运行 这种将字符串翻译成 pig latin 的方法时总是遇到同样的错误。

def pig_latin_word(word)
  new_arr = []
  letter = word.split("")

    if letter[0] == "a" || letter[0] == "e" || letter[0] == "i" || letter[0] == "o" || 
      letter[0] == "u"
      new_arr << "yay"
    else
      letter[0].shift && new_arr << letter[0].push + "ay"
    end
  return new_arr.join
end

# Test cases: 
puts pig_latin_word("eat")     # => "eatyay"
puts pig_latin_word("banana")  # => "ananabay"
puts pig_latin_word("trash")   # => "ashtray"

据我所知,您正在尝试转换为字母(字符串)。本质上,每当您执行字母 [0].shift 时,您就是在取消引用数组的第一个元素,它是一个字符串。 Shift 适用于数组。

这是一个代码片段,它完全符合您的要求。只有最后一个测试用例无法 return 给定您 post 代码的建议值。你说它应该 return "ashtray",但如果你移开第一个字母,将它附加到最后一个并添加 ay 你实际上应该得到 "rashtay"

def pig_latin_word(word)
  return "#{word}yay" if word =~ /^[AEIOUaeiou]/
  word_array = word.split('')
  latin_word = "#{word_array[0..word_array.length].join}#{word_array.shift}ay"

  return latin_word
end

puts pig_latin_word("eat")     # => "eatyay"
puts pig_latin_word("banana")  # => "ananabay"
puts pig_latin_word("trash")   # => "rashtay"

#shift#push 都是数组方法,您在 letter[0] 上调用它们,这是一个字符串。 即使您将此修复为使用 letter.shiftletter.push ,您仍然不会得到 "trash" => "ashtray" 除非您循环并从开头收集常量单词。

def pig_latin_word(word)
  exp = /^[AEIOUaeiou]/
  if word =~ exp
    word + "yay"
  else
    word.each_char
        .take_while {|c| c !~ exp }
        .yield_self do |consonants|
          word[consonants.length..-1] + consonants.join + "ay"
        end
  end
end
require 'minitest/autorun'
class PigLatinTest < Minitest::Test
  def test_word_that_begins_with_a_vowel
    assert_equal("eatyay", pig_latin_word("eat"))
  end
  def test_word_that_begins_with_a_consonant
    assert_equal("ananabay", pig_latin_word("banana"))
  end
  def test_word_that_begins_with_multiple_consonants
    assert_equal("ashtray", pig_latin_word("trash"))
  end
end
maxcal@pop-os ~/p/sandbox> ruby test.rb
Run options: --seed 59131

# Running:

...

Finished in 0.001205s, 2488.6889 runs/s, 2488.6889 assertions/s.
3 runs, 3 assertions, 0 failures, 0 errors, 0 skips

参见: