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.
Otherwise, if you change your variable to this: my_array = ["..\\\\..\\\\..\\\\Source\\\\file1.c", "..\\\\..\\\\..\\\\Source\\\\file2.c"]
your code should work.
UPDATE
if you can not control my_array
, and it is always an array of one item arrays, perhaps this is cleanest:
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. You want:
my_array.each {|n| puts n[0].gsub(/\\/,"//")}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.