我想在Ruby中创建一个类来检查类型,如果发现它没有想到的东西会引发错误。这是我到目前为止:Ruby:获取变量的名称
module LibHelper
class Base
def self.check_type(variables, types)
raise "Expected variables to be an array" unless variables.is_a?(Array)
raise "Expected types to be an array" unless types.is_a?(Array)
raise "Variable array and type array aren't same length" unless variables.length == types.length
variables.zip(types).each do |variable, type|
raise "Expected parameters in variables array to be symbols" unless variable.is_a?(Symbol)
raise "Expected #{eval(variable.to_s, binding)} to be type: #{type}" unless variable.is_a?(type)
end
end
def self.valid_type?(type)
valid_types = [String, Fixnum, NilClass, Hash, Symbol]
raise "Expected type to be String, Fixnum, NilClass, Hash, or Symbol got #{type}" unless valid_types.include?(type)
end
end
end
test_var = 'just_a_test_string'
LibHelper::Base.check_type([test_var], [String])
我的问题是什么是最好的方式来返回不是某种类型的变量的名称?我试图在这里这样做:
raise "Expected #{eval(variable.to_s, binding)} to be type: #{type}" unless variable.is_a?(type)
但它看起来像绑定可能不会通过范围?理想情况下,我的回报是'预期test_var是类型:字符串'
任何想法或想法?
或者如果你需要更多的信息“预期#{variable.inspect}被键入:#{type}” –
Tho se不会给你变量的名称,而是该变量的字符串表示。 OP正在询问名字。 –