Dave Dave - 1 year ago 107
Ruby Question

How do I apply my function to non-nil elements only?

I’m using Rails 4.2.7. I have this concise function that trims (strips) strings in my array

data_cols = data_cols.collect{|x| x.strip || x }

However if one of the elements in the array is nil, the above falls apart. How can I modify the above so that it won’t apply to nil elements?

Answer Source

If you want to remove nil values from the array entirely, you can use compact:

cols.compact.map { |col| col.strip } 
# or 

If you want to keep all values, but only operate on the non-nil values, you can simply use a nil-guard:

# straightforward, no magic, works across rubies:
cols.map { |col| col && col.strip || col }

# a wee dose of magic in ruby 2.3 (safe navigation operator)
cols.map { |col| col&.strip }

Finally, if you want to be more idiomatic and ruby-esque, you can use duck-typing and let the objects sort out themselves whether or not they can be "strip'ped":

cols.map { |col| col.strip if col.respond_to?(:strip) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download