开发者

Refactor regular expression call

I am new to regular expressions and I need help condensing the following code:

def finalize
  query = key
  query.each { |word| word.gsub!(/\s/, '_') }
  qu开发者_StackOverflow社区ery.each { |word| word.gsub!(/\W/, '') }
  yield [ query.join(":").downcase, key, aggregate_scores].flatten
end

Key is an array of (messy) strings that I want to condense into a query string, with all special characters blown away, spaces replaced with underscores, and joined by colons, so I can then yield that new string (query) with they key array unchanged.


Ruby encourages method chaining:

def finalize
  query = key.map { |word| word.gsub(/\s/, '_').gsub(/\W/, '') }.join(":").downcase
  yield [ query, key, aggregate_scores].flatten
end


For one thing, you can chain gsubs together:

word.gsub!(/\s/, '_').gsub!(/\W/, '')

I think this does the same:

yield [key.collect {|word| word.gsub(/\s/, '_').gsub(/\W/, '').downcase}.join(":"), key, aggregate_scores].flatten

But I also wonder why bother looping to do the gsubs.

yield [key.join(":").gsub(/\s/,'_').gsub(/[^\w:]/,"").downcase, key, aggregate_scores].flatten

that joins it all together, and then cleans it, ignoring colons. The only problem is if the original keys had colons, as they wouldn't get stripped.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜