提交 e1a72606 编写于 作者: S schneems

Use block variable instead of global


```ruby
require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("$&") {
    "foo".sub(/f/) { $&.upcase }
  }
  x.report("block var") {
    "foo".sub(/f/) {|match| match.upcase }
  }
end

```

```
Calculating -------------------------------------
                  $&    48.658k i/100ms
           block var    49.666k i/100ms
-------------------------------------------------
                  $&    873.156k (± 9.3%) i/s -      4.331M
           block var    969.744k (± 9.2%) i/s -      4.818M
```

It's faster, and gets rid of a few "magic" global variables
上级 f7c0d133
......@@ -55,7 +55,7 @@ def escape_segment(segment)
def unescape_uri(uri)
encoding = uri.encoding == US_ASCII ? UTF_8 : uri.encoding
uri.gsub(ESCAPED) { [$&[1, 2].hex].pack('C') }.force_encoding(encoding)
uri.gsub(ESCAPED) { |match| [match[1, 2].hex].pack('C') }.force_encoding(encoding)
end
protected
......
......@@ -68,9 +68,9 @@ def singularize(word, locale = :en)
def camelize(term, uppercase_first_letter = true)
string = term.to_s
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize }
else
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
end
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
string.gsub!('/'.freeze, '::'.freeze)
......
......@@ -117,9 +117,9 @@ rescue LoadError
def camelize(uppercase_first_letter = true)
string = self
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { $&.capitalize }
string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
else
string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { $&.downcase }
string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
end
string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub('/', '::')
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册