我正在迭代一个数组:
@fileArray.each() {
|x|
}
如何访问值x
以检查它是否以特定字符串开头?
答案 0 :(得分:8)
test = ['abc', 'bcef', 'abcdef']
p test.select{|word| word.start_with?('abc')}
#=> ["abc", "abcdef"]
# or the very short:
test.grep(/^abc/)
#=> ["abc", "abcdef"]
答案 1 :(得分:2)
这似乎可以解决问题!
test = ['abc', 'bcabcef', 'abcdef']
test.each do |x|
if x.match(/^abc/)
puts x
end
end
输出:
abc
abcdef
答案 2 :(得分:0)
您可以使用select。
["a","ab","b","ac","c"].select{|x| x[0] == "a"}
=> ["a", "ab", "ac"]
如果没有,那么你可以做到
x[0..5] == "String"