我有几个我想puts
经常调试的对象。
对象默认to_s
方法对于该目的并不是那么好。一般来说,我觉得你会想要查看实例(所以最有趣的部分是实例变量)所以我想出了这个:
class DebugObject
def initialize(args)
raise ArgumentError unless args.is_a? Hash
args.each { |k,v| instance_variable_set "@#{k}".to_sym,v }
end
def to_s
str = "#{self.class}:\n"
instance_variables.each do |var|
str += " %s: %s" % [var, instance_variable_get(var)]
end
str
end
end
class User < DebugObject
attrs = [:email, :password, :first_name, :last_name, :street, :postal_code, :city]
attrs.each { |attr| attr_accessor attr }
end
class CreditCard < DebugObject
attrs = [:holder, :number, :cardinalidity, :cvc, :error_code, :error_message]
attrs.each { |attr| attr_accessor attr }
end
与 puts 一起使用时给了我:
User:
@first_name: Peter @last_name: Parker @street: Street number @postal_code: 9020
@city: New york @email: peter@parker.com
CreditCard:
@holder: Martin @number: 00000 @cardinalidity: 09/10 @cvc: 123
@error_code: 00 @error_message: No eroro :)
我想知道您是否有任何提示和技巧来编写一个to_s
在调试时有用的出色、可重用的方法?