Ruby 返回以“wa”开头的数组中的第一个字
我有一个数组,它包含字符串和符号的混合体Ruby 返回以“wa”开头的数组中的第一个字,ruby,Ruby,我有一个数组,它包含字符串和符号的混合体 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
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
您需要将数组传递给您的方法,否则,它在方法的作用域中不可见。此外,我建议进行一次简单的重构:
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"
这里的确切问题是什么?detect是数组查找第一个匹配项的方法。请注意,以字母wa开头和以子字符串wa开头表示不同的含义。word.is_?String–变量名使此检查看起来多余:-