如何在不使用全局变量的情况下在Ruby中使用Logger而不是puts
我开始用它来练习Ruby。它给出了以下错误如何在不使用全局变量的情况下在Ruby中使用Logger而不是puts,ruby,Ruby,我开始用它来练习Ruby。它给出了以下错误 Use a logger instead of puts or add assertion. require_relative '../lib/soshisoai' file_path = File.expand_path('../../spec/fixtures/soshisoai3.txt', __FILE__) myarr1 = Soshisoai.parse_file(file_path) myarr2 = Soshisoai.get_c
Use a logger instead of puts or add assertion.
require_relative '../lib/soshisoai'
file_path = File.expand_path('../../spec/fixtures/soshisoai3.txt', __FILE__)
myarr1 = Soshisoai.parse_file(file_path)
myarr2 = Soshisoai.get_combi(myarr1)
myarr3 = Soshisoai.flat_arr(myarr2)
myarr4 = Soshisoai.eliminate_duplicate(myarr3)
myarr5 = Soshisoai.swap_male(myarr4)
myarr6 = Soshisoai.find_match(myarr5)
myarr7 = Soshisoai.delete_same_suffix(myarr6)
myarr8 = Soshisoai.delete_same_prefix(myarr7)
puts myarr8
Why
You don't want to clutter your logs with raw puts, pp, or p. Output using p
will not always appear in your logs, nor will it inherit from any log config
you may have (to add information such as the timestamp).
How to fix
In a Rails application
Use Rails.logger instead.
In Ruby code
Just use the Logger class.
In unit and integration tests
This is often a sign that you are missing some asserts and other checks.
然后,我使用了Logger,但它给出了另一个错误
Avoid global variable.
require_relative '../lib/soshisoai'
require 'logger'
$Log = Logger.new('log_file.log')
$Log.debug('Soshisoai3')
file_path = File.expand_path('../../spec/fixtures/soshisoai3.txt', __FILE__)
myarr1 = Soshisoai.parse_file(file_path)
myarr2 = Soshisoai.get_combi(myarr1)
myarr3 = Soshisoai.flat_arr(myarr2)
myarr4 = Soshisoai.eliminate_duplicate(myarr3)
myarr5 = Soshisoai.swap_male(myarr4)
myarr6 = Soshisoai.find_match(myarr5)
myarr7 = Soshisoai.delete_same_suffix(myarr6)
myarr8 = Soshisoai.delete_same_prefix(myarr7)
$Log.debug(myarr8)
Why
This check reports global variables. Global variables introduce strong dependencies
between otherwise unrelated parts of code and their usage is usually considered
extremely bad style.
How to fix
If you need a variable in many different places, here are some options other
than using a global
...
如何避免这些错误?如何使用实例变量 @log=Logger.new('log\u file.log')
然后,您可以在同一对象中使用@log。就像
Rails.logger所做的那样:将它作为一个类的实例变量(假设您没有使用Rails,否则您也可以使用Rails.logger
本身)。确保使用类的实例变量,而不是对象的实例变量。从技术上讲,这几乎是一个全局变量,但它应该足以避免PullReview
的投诉。差不多
require 'logger'
class MyApp
@logger=Logger.new("/tmp/log")
def self.logger
@logger
end
end
应该允许您毫无怨言地调用MyApp.logger
,当然,您可以自由使用任何您想要的日志类