2

I've got a string that I'm splitting, as follows:

foo, bar, baz, etc = str.split(',')

If, for example, str is equal to "one,two,,four", then baz ends up equalling "" (an empty string). Is there any easy way to loop through these for parameters to convert them to nil if they're an empty string? Or am I stuck doing the following?

foo = nil if foo.blank?
bar = nil if bar.blank?
baz = nil if baz.blank?
etc = nil if etc.blank?
2
  • 2
    why do you need it to be nil? Commented Jul 10, 2011 at 6:48
  • 1
    Because nil and empty string are two different values. Commented Jul 10, 2011 at 19:09

2 Answers 2

6

If you're doing this in rails, you can use the Object#presence method:

foo, bar, baz, etc = str.split(',').map(&:presence)
Sign up to request clarification or add additional context in comments.

Comments

4

I can suggest you this solution:

foo, bar, baz, etc = str.split(',').map{|ss| ss.blank? ? nil : ss}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.