Skip to content

Commit 6dcf64e

Browse files
committed
descendants はブロックを受けとらなくていい
1 parent ea00409 commit 6dcf64e

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

lib/tree_support/treeable.rb

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ def each_node(&block)
1717
each {|node| node.each_node(&block)}
1818
end
1919

20-
def descendants(&block)
21-
return enum_for(__method__) unless block_given?
22-
each do |node|
23-
yield node
24-
node.descendants(&block)
25-
end
20+
def descendants
21+
flat_map { |node| [node] + node.descendants }
22+
end
23+
24+
def self_and_descendants
25+
[self] + descendants
2626
end
2727

2828
def ancestors
@@ -46,7 +46,7 @@ def root?
4646
end
4747

4848
def leaf?
49-
children.size.zero?
49+
children.empty?
5050
end
5151
end
5252
end

test/test_treeable.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ class TestTreeable < Test::Unit::TestCase
2424
assert_equal ["a", "a1", "a2", "x", "a3"], @root.descendants.collect(&:name)
2525
end
2626

27+
test "self_and_descendants" do
28+
assert_equal ["*root*", "a", "a1", "a2", "x", "a3"], @root.self_and_descendants.collect(&:name)
29+
end
30+
2731
test "each_node" do
2832
assert_equal ["*root*", "a", "a1", "a2", "x", "a3"], @root.each_node.collect(&:name)
2933
end

0 commit comments

Comments
 (0)