2015-07-21 91 views
3

我想在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是类型:字符串'

任何想法或想法?

+0

或者如果你需要更多的信息“预期#{variable.inspect}被键入:#{type}” –

+0

Tho se不会给你变量的名称,而是该变量的字符串表示。 OP正在询问名字。 –

回答

3

这不起作用。

没有可靠的方法来检索对象分配给的变量名称。这是一个人为的例子:

def check_string(foo) 
    bar = foo 
    LibHelper::Base.check_type([bar], [String]) 
end 

var = 123 
check(var) 

在这种情况下,正确的错误信息是什么?

#=> Expected var to be type: String 
#=> Expected foo to be type: String 
#=> Expected bar to be type: String 

此外,您可以轻松地创建不分配给一个变量对象:

LibHelper::Base.check_type([123], [String]) 

一个更好的错误信息会是:

#=> Expected 123 to be type: String 

即只使用variable.inspect

+1

另一种方法是将绑定中的符号传入此方法,如:'LibHelper :: Base.check_type(self.send(:binding),[:test_var],[String])''。 – mudasobwa

+0

@mudasobwa是的,但这会限制检查当前范围内局部变量的方法。 – Stefan

+0

是的,这取决于OP实际需要什么。无论如何,我只是提到另一种可能性。 – mudasobwa