2014-02-21 17 views
0

我想在一個正則表達式使用命名組,但它不工作:命名紅寶石正則表達式和組

module Parser 
    def fill(line, pattern) 
    if /\s#{pattern}\:\s*(\w+)\s*\;/ =~ line 
     puts Regexp.last_match[1] 
     #self.send("#{pattern}=", value) 
    end 
    if /\s#{pattern}\:\s*(?<value>\w+)\s*\;/ =~ line 
     puts value 
     #self.send("#{pattern}=", value) 
    end 
    end 
end 

正如你可以看到我第一次測試我的正則表達式,然後我嘗試使用相同的正則表達式與一個命名的組。

class Test 
    attr_accessor :name, :type, :visible 
    include Parser #add instance method (use extend if we need class method) 
    def initialize(name) 
    @name = name 
    @type = "image" 
    @visible = true 
    end 
end 

t = Test.new("toto") 
s='desciption{ name: "toto.test"; type: RECT; mouse_events: 0;' 
puts t.type 
t.fill(s, "type") 
puts t.type 

當我執行這個,第一個正則表達式的工作,但不是第二個與指定的組。 這裏是輸出:

./ruby_mixin_test.rb 
image 
RECT 
./ruby_mixin_test.rb:11:in `fill': undefined local variable or method `value' for 
#<Test:0x00000001a572c8> (NameError) 
from ./ruby_mixin_test.rb:34:in `<main>' 

回答

5

如果=~使用具有文字名爲捕獲正則表達式中定義value,捕獲字符串(或無)被分配給本地由捕獲名稱命名的變量。

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ " x = y " 
p lhs #=> "x" 
p rhs #=> "y" 

但是 - 一個RegExp插值,#{},也禁止轉讓。

rhs_pat = /(?<rhs>\w+)/ 
/(?<lhs>\w+)\s*=\s*#{rhs_pat}/ =~ "x = y" 
lhs # undefined local variable 

在你的情況下,從下面的代碼:

if /\s#{pattern}\:\s*(?<value>\w+)\s*\;/ =~ line 
    puts value 
    #self.send("#{pattern}=", value) 
end 

看看下面的線,你用

/\s#{pattern}\:\s*(?<value>\w+)\s*\;/ =~ line 
~~^ 

因此局部變量賦值沒有發生並且您得到了錯誤,因爲您報告了未定義的d局部變量或方法'值'

+1

你的答案很無奈。你有一些消息來源嗎? – cedlemo

+0

@cedlemo已經給出 –

1

您還沒有該模塊

if /\s#{pattern}\:\s*(?<value>\w+)\s*\;/ =~ line 
    puts value # This is not defined anywhere 
    [..] 
+0

這是錯誤的答案... –