blu
blu

Reputation: 13175

What is the cleanest port of this C# to Ruby?

I am parsing a comma separated string into an array. In C# I have:

var someArray = someString.Split(
    new char[] { ',' },
    StringSplitOptions.RemoveEmptyEntries);

foreach (var something in someArray)
{
    SomeList.Add(something.Trim().ToLower());
}

Here is what I have so far in Ruby using Rails .blank?

some_array = some_string.split(',').each { |something| something.strip.downcase }
some_array.delete_if { |something| something.blank? }

Is there a cleaner way to do this?

Upvotes: 1

Views: 167

Answers (2)

Phrogz
Phrogz

Reputation: 303361

a) The code you have as written doesn't do what you expect. You call .each and call non-mutating methods on the strings. As a result, your some_array is the same as some_string.split(',').

b) I would personally do this:

arr = str.split(',').map{ |s| s.blank? ? nil : s.strip.downcase }.compact

This creates an array that may have nil entries, which are then removed with "compact". If absolute speed is of the essence, though, this will be faster:

arr = []
str.split(',').each do |s|
  arr << s.strip.downcase unless s.blank?
end

Edit: modified code to defer .strip.downcase until after testing for blankness.

Upvotes: 2

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369536

some_string.split(',').map(&:strip).map(&:downcase).reject(&:empty?)

This creates three intermediary arrays, and traverses all of three of them, but I wouldn't generally worry about that unless you can actually prove via performance profiling that it is a serious bottleneck.

Otherwise you'd have to do something like

some_string.split(',').inject([]) {|ary, str|
  ary.tap { unless (str = str.strip.downcase).empty? then ary << str end }
}

Sidenote: I'd probably have written that C# code more like this:

var someList = new List<string>(
    from s in someString.Split(
        new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
    select s.Trim().ToLower());

Upvotes: 3

Related Questions