arrays - Ruby: Remove whitespace chars at the beginning of a string -


this question has answer here:

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:

  1. delete_if {|x| x == ""} can replaced delete_if(&:empty?)
  2. except want reject! because delete_if return different array, rather modify existing one.
  3. words.each {|e| e.lstrip!} can replaced words.each(&:lstrip!)
  4. delete("\r") should redundant if you're reading windows-style text document on windows machine, or unix-style document on unix machine
  5. split(",") can replaced split(", ") or split(/, */) (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

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -