1

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

1
  • you need multidimensional array always ?, or result may be in single dimensional array ? Commented May 9, 2016 at 12:36

4 Answers 4

2

If you need result in single dimension then you can use simply:

[["yes", "yes", "yes"], []].flatten.compact
Sign up to request clarification or add additional context in comments.

Comments

1

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"]

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.