我不确定问题标题是否有意义,但这是我正在尝试做的事情。
我有一个包含数组的Rakefile。我希望能够使用另一个ruby脚本来读取Rakefile,向该数组添加内容,对其进行排序,然后将其写回到Rakefile中。
在伪代码中,这正是我本来想要实现的目标:
rake_file = load file('Rakefile')
rake_file.array += 'new data'
rake_file.array.sort!
file.write Rakefile
Rakefile包含许多数组和任务,因此我不能将其视为常规文本文件,只是将值附加到文件并进行排序,因此我的想法是加载它并编辑上面的数组。 / p>
这甚至可能吗?
答案 0 :(得分:0)
我不能像普通文本文件一样对待它
然后,您需要学习ANTLR,创建Ruby语法,生成解析器,并编写Java或C#或Python树步行器来编辑阵列。简单: - )
我想象一个快速而简单的解决方案。该数组保存在文件中,例如array_source.rb
:
a = [1, 5, 10, 15]
此文件可以手动编辑,或者,如果需要以编程方式生成使用脚本创建的数据,请说create_array_source.rb:
# update the file containing the array of data in text representation
array_source_name = 'array_source.rb'
a = [1, 5, 10, 15]
# add new data
[2, 6, 11, 16].each { | e | a << e }
puts a.join(' ')
# Write it to a file
File.open(array_source_name, 'w') do | out |
# to avoid a very long single line, the data is pretty printed
groups = []
a.sort.each_slice(4) { | slice | groups << slice.join(', ') }
out.puts ' ['
out.print ' '
out.puts groups.join(",\n ")
out.puts ' ]'
end
puts "#{array_source_name} has been created"
执行:
$ ruby -w create_array_source.rb
1 5 10 15 2 6 11 16
array_source.rb has been created
文件array_source.rb之后:
[
1, 2, 5, 6,
10, 11, 15, 16
]
在Rakefile中,要更新的数组放在两个特定标记之间:
task :default => [:ta, :tb] do
end
task :ta do
# $$insert array after$$
a = [1, 5, 10, 15]
# $$insert array before$$
# do something with a
end
task :tb do
# do something
end
因此,编写一个将其作为文本文件处理的脚本很容易,将这些行拆分为两部分:
然后通过连接第一部分,数组和第二部分来重写文件:
# modify a specific array in a Rakefile
rakefile_name = 'Rakefile'
array_source_name = 'array_source.rb'
lines = IO.readlines(rakefile_name)
insert_marker_after_seen = false
insert_marker_before_seen = false
lines1 = []
lines2 = IO.readlines(array_source_name)
lines3 = []
# split the Rakefile
lines.each do | line |
case
when insert_marker_after_seen == false
lines1 << line
if line.include?('$$insert array after$$')
then
insert_marker_after_seen = true
end
when ! insert_marker_before_seen
# ignore array lines
if line.include?('$$insert array before$$')
then
insert_marker_before_seen = true
lines3 << line
end
else
lines3 << line
end
end
# Rewrite the Rakefile
File.open(rakefile_name, 'w') do | out |
[ lines1, lines2, lines3 ].each do | lines_group |
lines_group.each { | line | out.puts line }
end
end
puts "#{rakefile_name} has been updated with #{array_source_name}"
执行:
$ ruby -w modify_rakefile.rb
Rakefile has been updated with array_source.rb
Rakefile之后:
task :default => [:ta, :tb] do
end
task :ta do
# $$insert array after$$
[
1, 2, 5, 6,
10, 11, 15, 16
]
# $$insert array before$$
# do something with a
end
task :tb do
# do something
end