views:

54

answers:

2

I found this code:

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

on this website: http://granth.ca/2006/02/strip-whitespace

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

I have tried a few different things, but cannot figure it out.

Thank you for any help

A: 

Pretty much the same, only you change each_key to a method to process every element of array (each) and self[a] to a (since you don't need to look into hash anymore).

.each {|a| a.strip! if a.respond_to? :strip! }

edit
An example

x = [" 1  ", "b", " c ", 5]
x.each {|a| a.strip! if a.respond_to? :strip! }
puts x.inspect

Output:

["1", "b", "c", 5]

No whitespaces on string ends anymore.

Nikita Rybak
I am doing row.each {|a| a.strip! if a.respond_to? :strip! } (and have tried row2 = row.each {|a| a.strip! if a.respond_to? :strip! } to make sure it wasn't that , but the items still have the white space. Not sure it helps, but I am doing this on a csv file that I am pulling in with FasterCSV. I could probably clean up the CSV output, but would be useful to know this for the future anyways.
Toby Joiner
@Toby Do you mean, it's not working? I've posted an example.
Nikita Rybak
@Toby (to updated comment) Check which type array elements have (e.g., `puts x[0].class`). If it's not a string, you can't use string's `strip!` method on them.
Nikita Rybak
turns out I am just dumb, I didn't know that if you use :headers => true, it would make each item an array with the header as the first element, and the value as the second, I got it to work on the second item, then found out it was just as easy to add -W to sqlcmd to output from mssql without the whitespace. Thanks for everyone's help.
Toby Joiner
+3  A: 

This is what collect is for.

yourArray.collect{|x| x.strip}

alternatively:

yourArray.collect(&:strip)

http://apidock.com/ruby/Array/collect

Jamie Wong