Melanie Shebel Melanie Shebel -4 years ago 192
Ruby Question

Ruby: Remove whitespace chars at the beginning of a string

I have an array of words where I am trying to remove any whitespace that may exist at the beginning of the word instead of at the end. rstrip! just takes care of the end of a string.

example_array = ['peanut', ' butter', 'sammiches']
desired_output = ['peanut', 'butter', 'sammiches']


As you can see, not all elements in the array have the whitespace problem, so I can't just delete the first character as I would if all elements started with a single whitespace char.

Full code:

words = params[:word].gsub("\n", ",").delete("\r").split(",")
words.delete_if {|x| x == ""}
words.each do |e|
e.lstrip!
end


Sample text that a user may enter on the form:

Corn on the cob,
Fibonacci,
StackOverflow
Chat, Meta, About
Badges
Tags,,
Unanswered
Ask Question

Answer Source

String#lstrip (or String#lstrip!) is what you're after.

desired_output = example_array.map(&:lstrip)

More comments about your code:

  1. delete_if {|x| x == ""} can be replaced with delete_if(&:empty?)
  2. Except you want reject! because delete_if will only return a different array, rather than modify the existing one.
  3. words.each {|e| e.lstrip!} can be replaced with words.each(&:lstrip!)
  4. 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 machine
  5. split(",") can be replaced with split(", ") or split(/, */) (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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download