2017-01-15 21 views
0

我目前正在使我的博客與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) 

不幸的是,它總是返回'字符串'即使我們有一個字符串「16」例如。

回答

0

下面的代碼做工精細

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"如果你不想忽略。希望它能幫助你。

+0

這不完全是我想要的,但我通過上下文獲取值來解決它。 –