类型检查不适用于 Ruby 和 Liquid

Type Checking does not work with Ruby and Liquid

我目前正在使用 Jekyll 制作我的博客。 Jekyll 自定义插件使用 Ruby 并且 Jekyll 使用 Liquid。我目前正在通过自定义液体标签获取输入并在那里进行处理。我想检查字符串是否包含整数。所以我有以下代码。我意识到输入不是 String 类型,而是 Jekyll::Token 类型。所以我将输入更改为字符串,但无法检测字符串是否包含整数。这是我的代码:

module Jekyll
    class TypecheckTag < Liquid::Tag

        def is_int(word)
            return word.count("0-3000") > 0
        end 

        def initialize(tag_name, word, tokens)
            super
            @word = word.to_s

        end

        def render(context)
            if /\A\d+\z/.match(@word)
                @result = 'int'
            else
                @result = 'string'
            end
        end


    end
end

Liquid::Template.register_tag('typecheck', Jekyll::TypecheckTag)

不幸的是,它总是 returns 'string' 说即使我们有一个字符串 "16" 例如。

下面的代码工作正常

def render(input_str) if /\A[-+]?\d+\z/.match(input_str.strip) @result = 'int' else @result = 'string' end end

带输出的示例输入

p render('16') # "int"
p render('16a') # "string"
p render('16  ')  # "int"
p render('asd') #"string"
p render('') #"string"

我使用 strip 因为 render('16 ') # "int" 如果你不想忽略它。希望对你有帮助。