我是ruby的新手,我想知道如何拆分包含特殊字符的元素。
我有以下数组:
my_array = ["sh.please-word", ".things-to-do" , "#cool-stuff", "span.please-word-not"]
my_array.slice!(0..1)
puts my_array
=>#cool-stuff
=>span.please-word
我想让它拆分不以点(。)或(#)开头的数组元素,并返回如下列表:
.please-word
.things-to-do
#cool_stuff
.please-word-not
我试图将切片方法用于完美的字符串,但是当我尝试使用数组元素时,它不起作用。
这是我到目前为止所做的。
list_of_selectors = []
file = File.open("my.txt")
file.each_line do |line|
list_of_selectors << line.split(' {')[0] if line.start_with? '.' or line.start_with? '#'
end
while line = file.gets
puts line
end
i = 0
while i < list_of_selectors.length
puts "#{list_of_selectors[i]}"
i += 1
end
list = []
list_of_selectors.each { |x|
list.push(x.to_s.split(' '))
}
list_of_selectors = list
puts list_of_selectors
list_of_selectors.map! { |e| e[/[.#].*/]}
puts list_of_selectors
答案 0 :(得分:2)
result_array = my_array.map { |x| x[/[.#].*/] }
# => [".please-word", ".things-to-do", "#cool-stuff", ".please-word-not"]
上面使用正则表达式来提取文本,从点(.
)或主题标签(#
)开始,并在结果数组中返回。