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.
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 .
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.
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.
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
If you don't mind first removing nil
elements:
YourArray.compact.collect(&:strip)
https://ruby-doc.org/core/Array.html#method-i-compact
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With