0

How do I get rid of whitespaces and blank items in an array

names = ["alice", "", "bob", " ", "yankee"]

desired result should be

["alice", "bob", "yankee"]
xpnimi
  • 167
  • 1
  • 1
  • 13
  • 3
    I think you've made a mistake with your *should get* array. – Sagar Pandya Apr 20 '18 at 08:40
  • ok, re phrased it, I don't think it's a dup question, all I found was to use `.reject` which doesn't reject spaces and blank items in an array, Ursus answer helped me a lot! – xpnimi Apr 20 '18 at 09:16
  • Look at the elements in your second array, they are not from the first array. – Sagar Pandya Apr 20 '18 at 09:18
  • "Marked as a duplicate" except this is tagged ruby-on-rails and ruby, and the duplicate is marked just ruby, which gives other answers. E.g. in rails I would prefer using `blank?` and `present?` while in the duplicate they (obviously) prefer `empty?` which is only available on strings (but is pure ruby). – nathanvda Apr 20 '18 at 09:22
  • How did this question get upvoted? – Jagdeep Singh Apr 20 '18 at 10:33

2 Answers2

5

In rails is simple, use present?

names.select(&:present?)
Ursus
  • 29,643
  • 3
  • 33
  • 50
0

If you try this below it will provide you with a new array assigned to newNames that does not include the empty elements.

newNames = names.reject { |n| n.empty? }
Quinlayen
  • 52
  • 1
  • 2
  • 8