Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -852,4 +852,17 @@ def to_set(klass = Set, *args, &block)
end unless method_defined?(:to_set)
end

class Hash
# Returns a new Set containing keys from the Hash
#
# h = {a: 1, b: 3}
# h.keys_to_set #=> Set[:a, :b]
#
def keys_to_set
set = Set.new
set.instance_variable_set(:@hash, transform_values { true })
set
end
end

autoload :SortedSet, "#{__dir__}/set/sorted_set"
10 changes: 10 additions & 0 deletions test/test_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,16 @@ def test_to_set
end
end

class TC_Hash < Test::Unit::TestCase
def test_keys_to_set
h = {a: 2, b: 1, c: 37}
set = h.keys_to_set
expected = Set.new(h.keys)

assert_equal(set, expected)
end
end

class TC_Set_Builtin < Test::Unit::TestCase
private def should_omit?
(RUBY_VERSION.scan(/\d+/).map(&:to_i) <=> [3, 2]) < 0 ||
Expand Down