English 中文(简体)
采用选取而不是选取子,以避免在Ruby进行多次reg评价
原标题:Using select rather than gsub to avoid multiple regex evaluations in Ruby

这里的一项产出要求进行多次评价,但得到我想要做的工作(删除除案文外的一切)。

words = IO.read("file.txt").
gsub(/s/, ""). # delete white spaces
gsub(".",""). # delete periods
gsub(",",""). # delete commas
gsub("?","") # delete Q marks
puts words
# output
#      WheninthecourseofhumaneventsitbecomesnecessaryIwanttobelieveyoureallyIdobutwhoamItoblameWhenthefactsarecountedthenumberswillbereportedLotsoflaughsCharlieIthinkIheardthatonetentimesbefore

看看这个员额————我表示,如果不进行多次考试,我将尽力取得相同结果。 但我没有获得同样的产出。

words = IO.read("file.txt").
match(/(w*)+/)
puts words
# output - this only gets the first word
# When

这只是第一句:

words = IO.read("file.txt").
match(/(...*)+/)
puts words

# output - this only gets the first sentence
# When in the course of human events it becomes necessary.

任何关于获得相同产出的建议(包括排除白天空间和非口号)与相对比的建议?

最佳回答

你们可以在一项次要行动中做你们想要做的事情:

s =  When in the course of human events it becomes necessary. 
s.gsub /[s.,?]/,   
# => "Wheninthecourseofhumaneventsitbecomesnecessary"
问题回答

你们不需要对此进行多次评价。

str = "# output - this only gets the first sentence
# When in the course of human events it becomes necessary."
p str.gsub(/W/, "")
#=>"outputthisonlygetsthefirstsentenceWheninthecourseofhumaneventsitbecomesnecessary"




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签