Skip to content

Commit

Permalink
Merge pull request #5154 from maxpowa/array-reject-compact-select-cha…
Browse files Browse the repository at this point in the history
…ining

Allow chaining Array methods
  • Loading branch information
asterite authored Oct 20, 2017
2 parents 74a30e8 + e936233 commit 7bbb400
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 33 deletions.
33 changes: 5 additions & 28 deletions spec/std/array_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -354,18 +354,11 @@ describe "Array" do
a.should eq([1, nil, 2, nil, 3])
end

describe "compact!" do
it "returns true if removed" do
a = [1, nil, 2, nil, 3]
b = a.compact!.should be_true
a.should eq([1, 2, 3])
end

it "returns false if not removed" do
a = [1]
b = a.compact!.should be_false
a.should eq([1])
end
it "does compact!" do
a = [1, nil, 2, nil, 3]
b = a.compact!
b.should eq([1, 2, 3])
b.should be(a)
end

describe "concat" do
Expand Down Expand Up @@ -1307,14 +1300,6 @@ describe "Array" do
ary2.should be(ary1)
end

it "returns nil when using select! and no changes were made" do
ary1 = [1, 2, 3, 4, 5]

ary2 = ary1.select! { true }
ary2.should eq(nil)
ary1.should eq([1, 2, 3, 4, 5])
end

it "rejects!" do
ary1 = [1, 2, 3, 4, 5]

Expand All @@ -1323,14 +1308,6 @@ describe "Array" do
ary2.should be(ary1)
end

it "returns nil when using reject! and no changes were made" do
ary1 = [1, 2, 3, 4, 5]

ary2 = ary1.reject! { false }
ary2.should eq(nil)
ary1.should eq([1, 2, 3, 4, 5])
end

it "does map_with_index" do
ary = [1, 1, 2, 2]
ary2 = ary.map_with_index { |e, i| e + i }
Expand Down
11 changes: 6 additions & 5 deletions src/array.cr
Original file line number Diff line number Diff line change
Expand Up @@ -541,15 +541,15 @@ class Array(T)
compact_map &.itself
end

# Removes all `nil` elements from `self`.
# Removes all `nil` elements from `self` and returns `self`.
#
# ```
# ary = ["a", nil, "b", nil, "c"]
# ary.compact!
# ary # => ["a", "b", "c"]
# ```
def compact!
!!(reject! &.nil?)
reject! &.nil?
end

# Appends the elements of *other* to `self`, and returns `self`.
Expand Down Expand Up @@ -888,19 +888,20 @@ class Array(T)
end

# Modifies `self`, keeping only the elements in the collection for which the
# passed block returns `true`. Returns `nil` if no changes were made.
# passed block returns `true`. Returns `self`.
#
# See also: `Array#select`.
def select!
reject! { |elem| !yield(elem) }
end

# Modifies `self`, deleting the elements in the collection for which the
# passed block returns `true`. Returns `nil` if no changes were made.
# passed block returns `true`. Returns `self`.
#
# See also: `Array#reject`.
def reject!
internal_delete { |e| yield e }[0]
internal_delete { |e| yield e }
self
end

# `reject!` and `delete` implementation: returns a tuple {x, y}
Expand Down

0 comments on commit 7bbb400

Please sign in to comment.