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?
a) The code you have as written doesn’t do what you expect. You call
.eachand call non-mutating methods on the strings. As a result, yoursome_arrayis the same assome_string.split(',').b) I would personally do this:
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:
Edit: modified code to defer
.strip.downcaseuntil after testing for blankness.