[英]Can using the ruby flip-flop as a filter be made less kludgy?
為了獲得部分文本,我在觸發器前面使用了一個true if
kludge:
desired_portion_lines = text.each_line.find_all do |line|
true if line =~ /start_regex/ .. line =~ /finish_regex/
end
desired_portion = desired_portion_lines.join
如果我刪除了true if
位,它會抱怨
范圍的錯誤值(ArgumentError)
有可能減少它的價值,或者我應該這樣做
desired_portion_lines = ""
text.each_line do |line|
desired_portion_lines << line if line =~ /start_regex/ .. line =~ /finish_regex/
end
或者是否有更好的方法不使用枚舉?
如果你是逐行做的,我的偏好是這樣的
line =~ /finish_regex/ && p=0
line =~ /start_regex/ && p=1
puts line if p
如果你有一個字符串。 我會用拆分
mystring.split(/finish_regex/).each do |item|
if item[/start_regex/]
puts item.split(/start_regex/)[-1]
end
end
我認為
desired_portion_lines = ""
text.each_line do |line|
desired_portion_lines << line if line =~ /start_regex/ .. line =~ /finish_regex/
end
完全可以接受。 ..
運算符非常強大,但很多人都沒有使用它,可能是因為它們不了解它的作用。 可能它看起來很奇怪或尷尬,因為你不習慣使用它,但它會在你身上成長。 在處理文本文件中的行范圍時,它在Perl中非常常見,這是我第一次遇到它,並最終使用它很多。
我唯一不同的做法是添加一些括號,以便在邏輯上將邏輯測試彼此分開,並從行的其余部分:
desired_portion_lines = ""
text.each_line do |line|
desired_portion_lines << line if ( (line =~ /start_regex/) .. (line =~ /finish_regex/) )
end
Ruby(和Perl)編碼器似乎厭惡使用括號,但我認為它們對於在視覺上分離邏輯測試很有用。 對我來說,這是一個可讀性,並且,通過擴展,它是一個維護的東西。
我能想到的另一件事可能會有所幫助,那就是將desired_portion_lines
更改為一個數組,然后將選定的行推到它上面。 目前,使用desired_portion_lines << line
追加到字符串,每次都要改變它。 推送數組然后加入其元素以構建字符串可能會更快。
回到第一個例子。 我沒有對此進行測試,但我認為您可以將其簡化為:
desired_portion = text.each_line.find_all { |line| line =~ /start_regex/ .. line =~ /finish_regex/ }.join
使用觸發器迭代文件中所有行的唯一缺點是,如果啟動模式可以多次出現,則會將每個找到的塊添加到desired_portion
。
true if
使用!!()
(觸發器屬於括號之間!!()
,則可以通過替換true if
來保存三個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.