我有一个包含字符串和符号混合的数组。
array = ["candy", :pepper, "wall", :ball, "wacky"]
目标是返回以字母"wa"
开头的第一个单词。
这是我的代码:
def starts_with_wa
deleted_words = array.delete_if{|word| word.class == Symbol}
## deletes the symbols in the original array
deleted_words.find do |w|
##it should iterate through the deleted_Words array but it shows error of undefined local variable or method "array" for main:Object
w.start_with?('wa')
end
end
starts_with_wa
答案 0 :(得分:2)
您需要将array
传递给您的方法,否则,它在方法范围内将不可见。此外,我建议一个简单的重构:
array = ["candy", :pepper, "wall", :ball, "wacky"]
def starts_with_wa(words)
words.find { |word| word.is_a?(String) && word.start_with?('wa') }
end
starts_with_wa(array)
#=> "wall"
答案 1 :(得分:0)
您可以尝试以下操作
array.detect { |x| x.is_a?(String) && x.start_with?('wa') }