简体   繁体   English

如何将gsub应用于数组中的字符串元素?

[英]how to apply gsub on string elements within an array?

for example, I have an array which is structured as follow: 例如,我有一个结构如下的数组:

my_array = [["..\\..\\..\\Source\\file1.c"], ["..\\..\\..\\Source\\file2.c"]]

This array is produced by this code: 该数组由以下代码生成:

File.open(file_name) do |f|
    f.each_line {|line|
      if line =~ /<ClCompile Include="..\\/
        my_array << line.scan(/".*.c"/)
      end
    }
  end

Later in the code I'm working on the array: 在稍后的代码中,我正在处理数组:

my_array .each {|n| f.puts n.gsub(/\\/,"//")}

As you can see, would like to replace all the backslashes with forward slashes on the elements within the array. 如您所见,想用数组中元素上的正斜杠替换所有反斜杠。 The elements presents paths to source files. 元素提供了源文件的路径。 On the end I will output these paths within an other file. 最后,我将在另一个文件中输出这些路径。

I get this error: 我收到此错误:

undefined method `gsub' for [["..\\..\\..\\Source\\file1.c"], ["..\\..\\..\\Source\\file2.c"]]:Array (NoMethodError)

Any idea? 任何想法?

You have an array of arrays, so if you want to keep it like that, you would need to have 2 loops. 您有一个数组数组,因此,如果要保持这样的数组,则需要有2个循环。

Otherwise, if you change your variable to this: my_array = ["..\\\\..\\\\..\\\\Source\\\\file1.c", "..\\\\..\\\\..\\\\Source\\\\file2.c"] your code should work. 否则,如果将变量更改为此: my_array = ["..\\\\..\\\\..\\\\Source\\\\file1.c", "..\\\\..\\\\..\\\\Source\\\\file2.c"]您的代码应该可以正常工作。


UPDATE UPDATE

if you can not control my_array , and it is always an array of one item arrays, perhaps this is cleanest: 如果您无法控制my_array ,并且它始终是一个单项数组的数组,也许这是最干净的:

my_array.flatten.each {|n| puts n.gsub(/\\/,"//")}

What it does is transforms two-dimensional array in one-dimensional. 它所做的是将二维数组转换为一维。

my_array.flatten.each { |n| f.puts n.tr('\\', '/') }

As others have pointed out, you are calling gsub on an array, not the string within it. 正如其他人指出的那样,您是在数组上而不是其中的字符串调用gsub。 You want: 你要:

my_array.each {|n| puts n[0].gsub(/\\/,"//")}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM