Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 之前拆分数组元素。平均数数组_Ruby_Arrays - Fatal编程技术网

Ruby 之前拆分数组元素。平均数数组

Ruby 之前拆分数组元素。平均数数组,ruby,arrays,Ruby,Arrays,我是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 .thi

我是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
我尝试对一个字符串使用slice方法,但当我尝试使用数组元素时,它不起作用

这就是我到目前为止所做的

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
选择器列表=[]
file=file.open(“my.txt”)
file.u每行do |行|
选择器的列表

上面使用正则表达式来提取文本,从点(
)或哈希标记(
#
)开始,并将其返回到结果数组中。

数组来自何处?它来自一个文件,我在其中创建并清空数组并读取每一行,并检查行是以(#)哈希标记还是(.)点开始,并在循环中迭代。迭代之后,我在有空格的地方拆分每个元素,并将其添加到新的数组列表中。在此之后,我想分割所有不以(.)点开头的元素。e、 g li.ui-native-tabs。这应该被拆分为一个新数组。我尝试使用正则表达式,但仍然得到了跨度。请注意,我已经在发布代码时运行了代码,并得到了发布结果。你能给我看一下你运行的确切代码吗?我的数组=[“sh.please-word”、“.things to do”、“#cool stuff”、“span.please-word”]我的数组.map{e | e[/[.#].*/}现在我明白了。我已经更新了我的答案-
我的数组
没有改变,
结果数组
是被截断的数据。如果要更改数组本身,请使用
map
而不是
map
。现在它可以工作了,关于我的代码,它说它不能将Regexp转换为整数。我试图实现的是,从拆分列表中,我想提取不以点(.)开头的行,我将粘贴下面的代码
result_array = my_array.map { |x| x[/[.#].*/] }
# => [".please-word", ".things-to-do", "#cool-stuff", ".please-word-not"]