我想在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正在詢問名字。 –