[英]Pass variable in Ruby how?
Following my other question that was brilliantly solved How to generate a file with the names of the methods in class? 按照我的另一个问题,出色地解决了如何使用类中的方法名称生成文件?
Now I have another problem regarding code: 现在我有关于代码的另一个问题:
basedir = "."
files = Dir.new(basedir).entries
files.each do |file|
tests = file.match(/(.+)_tests.rb/)
puts tests if tests
end
#here i need to use "tests" variable again ..
tests.each do |test|
File.open(test).each_line do |line|
match = line.match(/def (.+)/)
puts match[1] if match
end
end
Gives me the mistake: 给我错误:
match_test_methods.rb:10: undefined local variable or method `tests' for main:Object (NameError)
I guess, the problem is that "tests" variable is born and buried in the files.each do method. 我想,问题是“测试”变量诞生并埋没在files.each做法中。 How can I use it globally? 我如何在全球范围内使用它? Nothing worked so far... 到目前为止没有任何工作......
Thanks. 谢谢。
You could define it before the iteration: 您可以在迭代之前定义它:
tests = nil
basedir = "."
files = Dir.new(basedir).entries
files.each do |file|
tests = file.match(/(.+)_tests.rb/)
puts tests if tests
end
# now tests will be available here
You could condense this down into a single loop, to negate the need to define tests
at a higher level. 您可以将其压缩为单个循环,以消除在更高级别定义tests
的需要。
basedir = "."
files = Dir.new(basedir).entries
files.each do |file|
tests = file.match(/(.+)_tests.rb/)
if tests
puts tests
File.open(file).each_line do |line|
match = line.match(/def (.+)/)
puts match[1] if match
end
end
end
Solved the problem by fixing the code: 通过修复代码解决了这个问题:
tests = []
basedir = "."
files = Dir.new(basedir).entries
tests = files.select do |file|
file.match(/(.+)_tests.rb/)
end
tests.each do |test|
puts test
File.open(test).each_line do |line|
if match = line.match(/def (.+)/)
puts match[1]
end
end
end
The problem was that the first method didn't return the array.. 问题是第一个方法没有返回数组..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.