2015-07-21 90 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