Ruby: Remove whitespace chars at the beginning of a string
> ' string '.lstrip.chop
=> "string"
Strips both white spaces...
String#lstrip
(or String#lstrip!
) is what you're after.
desired_output = example_array.map(&:lstrip)
More comments about your code:
delete_if {|x| x == ""}
can be replaced withdelete_if(&:empty?)
- Except you want
reject!
becausedelete_if
will only return a different array, rather than modify the existing one. words.each {|e| e.lstrip!}
can be replaced withwords.each(&:lstrip!)
delete("\r")
should be redundant if you're reading a windows-style text document on a Windows machine, or a Unix-style document on a Unix machinesplit(",")
can be replaced withsplit(", ")
orsplit(/, */)
(or/, ?/
if there should be at most one space)
So now it looks like:
words = params[:word].gsub("\n", ",").split(/, ?/)
words.reject!(&:empty?)
words.each(&:lstrip!)
I'd be able to give more advice if you had the sample text available.
Edit: Ok, here goes:
temp_array = text.split("\n").map do |line|
fields = line.split(/, */)
non_empty_fields = fields.reject(&:empty?)
end
temp_array.flatten(1)
The methods used are String#split
, Enumerable#map
, Enumerable#reject
and Array#flatten
.
Ruby also has libraries for parsing comma seperated files, but I think they're a little different between 1.8 and 1.9.