Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bff952a

Browse files
committed
allow RegexpTrie.new(patterns).to_source
1 parent f6e27a9 commit bff952a

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

‎lib/regexp_trie.rb‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,20 @@ class RegexpTrie
66
# @param [Fixnum,Boolean] option The second argument of Regexp.new()
77
# @return [Regexp]
88
def self.union(*strings, option: nil)
9-
rt = new
10-
strings.flatten.each do |arg|
11-
rt.add(arg)
12-
end
13-
rt.to_regexp(option)
9+
new(*strings).to_regexp(option)
1410
end
1511

16-
def initialize
12+
def initialize(*strings)
1713
@head = {}
14+
15+
strings.flatten.each do |str|
16+
add(str)
17+
end
1818
end
1919

2020
# @param [String] str
2121
def add(str)
22-
return self unlessstr && str.size > 0
22+
return self if !str || str.empty?
2323

2424
entry = @head
2525
str.each_char do |c|
@@ -30,15 +30,20 @@ def add(str)
3030
self
3131
end
3232

33-
# @return [Regexp]
34-
def to_regexp(option=nil)
33+
# @return [String]
34+
def to_source
3535
if @head.empty?
36-
Regexp.union
36+
Regexp.union.source
3737
else
38-
Regexp.new(build(@head),option)
38+
build(@head)
3939
end
4040
end
4141

42+
# @return [Regexp]
43+
def to_regexp(option = nil)
44+
Regexp.new(to_source, option)
45+
end
46+
4247
private
4348

4449
def build(entry)

‎test/regexp_trie_test.rb‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@ def test_union_rx
4949
assert { RegexpTrie.union('foo', 'bar', 'baz') == /(?:foo|ba[rz])/ }
5050
end
5151

52+
def test_union_source
53+
assert { RegexpTrie.new('a').to_source == 'a' }
54+
assert { RegexpTrie.new('a', 'aa').to_source == 'aa?' }
55+
assert { RegexpTrie.new('a', 'b').to_source == '[ab]' }
56+
assert { RegexpTrie.new('foo', 'bar').to_source == '(?:foo|bar)' }
57+
assert { RegexpTrie.new('foo', 'bar', 'baz').to_source == '(?:foo|ba[rz])' }
58+
end
59+
5260
def test_union_empty
5361
assert { RegexpTrie.union == Regexp.union }
5462
end

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /