arrays - Ruby: Remove whitespace chars at the beginning of a string -
this question has answer here:
- ruby function remove white spaces? 20 answers
i have array of words trying remove whitespace may exist @ beginning of word instead of @ end. rstrip! takes care of end of string.
example_array = ['peanut', ' butter', 'sammiches'] desired_output = ['peanut', 'butter', 'sammiches'] as can see, not elements in array have whitespace problem, can't delete first character if elements started single whitespace char.
full code:
words = params[:word].gsub("\n", ",").delete("\r").split(",") words.delete_if {|x| x == ""} words.each |e| e.lstrip! end sample text user may enter on form:
corn on cob, fibonacci, stackoverflow chat, meta, badges tags,, unanswered ask question
string#lstrip (or string#lstrip!) what you're after.
desired_output = example_array.map(&:lstrip) more comments code:
delete_if {|x| x == ""}can replaceddelete_if(&:empty?)- except want
reject!becausedelete_ifreturn different array, rather modify existing one. words.each {|e| e.lstrip!}can replacedwords.each(&:lstrip!)delete("\r")should redundant if you're reading windows-style text document on windows machine, or unix-style document on unix machinesplit(",")can replacedsplit(", ")orsplit(/, */)(or/, ?/if there should @ 1 space)
so looks like:
words = params[:word].gsub("\n", ",").split(/, ?/) words.reject!(&:empty?) words.each(&:lstrip!) i'd able give more advice if had sample text available.
edit: ok, here goes:
temp_array = text.split("\n").map |line| fields = line.split(/, */) non_empty_fields = fields.reject(&:empty?) end temp_array.flatten(1) the methods used string#split, enumerable#map, enumerable#reject , array#flatten.
ruby has libraries parsing comma seperated files, think they're little different between 1.8 , 1.9.
Comments
Post a Comment