Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby (Rails): remove whitespace from each array item

I found this code:

.each_key {|a| self[a].strip! if self[a].respond_to? :strip! } 

...but it is for a hash, whereas I am trying to do the same with an array.

like image 316
Toby Joiner Avatar asked Oct 13 '10 17:10

Toby Joiner


People also ask

How do you remove white spaces in Ruby?

If you want to remove only leading and trailing whitespace (like PHP's trim) you can use . strip , but if you want to remove all whitespace, you can use . gsub(/\s+/, "") instead .

What does .first do Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

How do you remove a value from an array in Ruby?

Ruby | Array delete() operation Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.


2 Answers

This is what collect is for.

The following handles nil elements by leaving them alone:

yourArray.collect{ |e| e ? e.strip : e } 

If there are no nil elements, you may use:

yourArray.collect(&:strip) 

...which is short for:

yourArray.collect { |e| e.strip } 

strip! behaves similarly, but it converts already "stripped" strings to nil:

[' a', ' b ', 'c ', 'd'].collect(&:strip!) => ["a", "b", "c", nil] 

https://ruby-doc.org/core/Array.html#method-i-collect

https://ruby-doc.org/core/String.html#method-i-strip

like image 116
Jamie Wong Avatar answered Oct 14 '22 16:10

Jamie Wong


If you don't mind first removing nil elements:

YourArray.compact.collect(&:strip)  

https://ruby-doc.org/core/Array.html#method-i-compact

like image 32
Gvlamadrid Avatar answered Oct 14 '22 15:10

Gvlamadrid