[英]How does an isolated regular expression get evaluated
我到處都看到這個片段,它有效! 為什么?
while gets
print if /start/../end/
end
ruby如何評估/start/
沒有Lvalue? 我希望我們首先必須將“獲取”的值存儲在某個地方然后再進行
gets_result =~ /start/.. gets_result =~ /end/
那么為什么代碼片段有效呢?
讓我澄清一下。
ruby如何知道將正則表達式與gets進行比較在上面的代碼片段中,我沒有指定ruby將reg exp與之比較gets
但是它只知道。 問題是怎么樣的?
好問題。
記住:當在條件語句中使用Range
運算符( ..
或...
)時,它會完全出乎意料:它不會創建Range
對象。 相反,它充當“觸發器”操作員。
實際上是下面的代碼
while gets
print if /start/../end/
end
默認是
while gets
# gets_input I put just to make the code more expressive
# actually the input taken using gets method applied here implicitly.
print if /start/ =~ gets_input .. /end/ =~ gets_input
end
讓我來證明你。 我接受了Ruby Tracer
類的幫助。
trace = TracePoint.new do |tp|
p [tp.lineno, tp.event, tp.defined_class,tp.method_id]
end
trace.enable do
while gets
# when you type start in your console, 11 will be output.
print 11 if /start/../end/
end
end
讓我運行這段代碼,向您展示我的上述代碼作為證明以及Ruby Flip-Flop功能:
(arup~>Ruby)$ ruby test.rb
test.rb:6: warning: regex literal in condition
test.rb:6: warning: regex literal in condition
[4, :b_call, nil, nil]
[5, :line, nil, nil]
[5, :c_call, Kernel, :gets]
[5, :c_call, ARGF.class, :gets]
end # I presses **end** here.
[5, :c_return, ARGF.class, :gets]
[5, :c_return, Kernel, :gets]
[6, :line, nil, nil]
# Regexp#=~ call begin happened for /end/ =~ gets_input
[6, :c_call, Regexp, :=~]
# Regexp#=~ call end happened for /end/ =~ gets_input
[6, :c_return, Regexp, :=~]
[5, :c_call, Kernel, :gets]
[5, :c_call, ARGF.class, :gets]
start # I presses **start** here.
[5, :c_return, ARGF.class, :gets]
[5, :c_return, Kernel, :gets]
[6, :line, nil, nil]
# Regexp#=~ call begin happened for /start/ =~ gets_input
[6, :c_call, Regexp, :=~]
# Regexp#=~ call end happened for /start/ =~ gets_input
[6, :c_return, Regexp, :=~]
# Regexp#=~ call begin happened for /end/ =~ gets_input
[6, :c_call, Regexp, :=~]
# Regexp#=~ call end happened for /end/ =~ gets_input
[6, :c_return, Regexp, :=~]
[6, :c_call, Kernel, :print]
[6, :c_call, IO, :write]
[6, :c_call, Fixnum, :to_s]
[6, :c_return, Fixnum, :to_s]
# As there is a match so **if** clause true, thus 11 printed
11[6, :c_return, IO, :write]
[6, :c_return, Kernel, :print]
[5, :c_call, Kernel, :gets]
[5, :c_call, ARGF.class, :gets]
end
[5, :c_return, ARGF.class, :gets]
[5, :c_return, Kernel, :gets]
[6, :line, nil, nil]
[6, :c_call, Regexp, :=~]
[6, :c_return, Regexp, :=~]
[6, :c_call, Kernel, :print]
[6, :c_call, IO, :write]
[6, :c_call, Fixnum, :to_s]
[6, :c_return, Fixnum, :to_s]
11[6, :c_return, IO, :write]
[6, :c_return, Kernel, :print]
[5, :c_call, Kernel, :gets]
[5, :c_call, ARGF.class, :gets]
在這種情況下, ..
是觸發器操作符。 當給出'start'時,條件計算為true,並且繼續為true
直到給出end
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.