Reputation: 1323
i have an array of arrays. from this i want to eliminate the empty arrays.
iam using reject!(&:empty?)
method. but it is giving me unexpected results.
2.2.2 :306 > array = ["yes","yes","yes"]
=> ["yes", "yes", "yes"]
2.2.2 :307 > array.split("no")
=> [["yes", "yes", "yes"]]
2.2.2 :308 > array.split("no").reject!(&:empty?)
=> nil
2.2.2 :309 > array_with_no = ["yes","yes","yes","no"]
=> ["yes", "yes", "yes", "no"]
2.2.2 :310 > array_with_no.split("no")
=> [["yes", "yes", "yes"], []]
2.2.2 :311 > array.split("no").reject!(&:empty?)
=> nil
2.2.2 :312 > array_with_no.split("no").reject!(&:empty?)
=> [["yes", "yes", "yes"]]
2.2.2 :313 >
i want the result where when there is no empty array to eliminate, then it should return the same array instead of returning nil
Upvotes: 1
Views: 1787
Reputation: 146
You can use delete_if
:
array = [["yes","yes","yes"], [], []]
array.delete_if{|x| x.empty?}
it will return [["yes","yes","yes"]
Or if you want to combine array of arrays you may use flatten
:
array = ["yes","yes","yes"], [], []].flatten
it will return ["yes","yes","yes"]
Upvotes: 1
Reputation: 3275
Use select.
array.split("no").select(&:present?)
=> [["yes", "yes", "yes"]]
Alternatively you can remove the bang from your reject and that will also give you what you want.
array.split("no").reject(&:empty?)
=> [["yes", "yes", "yes"]]
The ! on reject! will destructively modify the array in place and will return nil if no changes were made.
Upvotes: 0
Reputation: 2034
If you need result in single dimension then you can use simply:
[["yes", "yes", "yes"], []].flatten.compact
Upvotes: 2
Reputation: 1368
You want reject
instead of reject!
(the !-version modifies the array in-place and returns true
or nil
depending on if changes to the array were made or not)
Documentation on what the methods do
Upvotes: 0