29

I usually do

 value = input || "default"

so if input = nil

 value = "default"

But how can I do this so instead of nil It also counts an empty string '' as nil

I want so that if I do

input = ''
value = input || "default"
=> "default"

Is there a simple elegant way to do this without if?

2
  • Note that you tagged your question as ruby-on-rails, hence the Rails specific answers. Commented Jan 20, 2013 at 3:12
  • Yes I was running on rails so its no problem, I also tagged ruby because it looked more of a ruby problem-edited the title to match answers/question better Commented Jan 20, 2013 at 6:46

3 Answers 3

68

Rails adds presence method to all object that does exactly what you want

input = ''
value = input.presence || "default"
=> "default"

input = 'value'
value = input.presence || "default"
=> "value"

input = nil
value = input.presence || "default"
=> "default"
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, but it's RAILS_ONLY, 'pure' ruby does not have it.
Yes, it's Rails extension, as well as blank?
6

I usually do in this way:

value = input.blank? ? "default" : input

In response to the case that input might not be defined, you may guard it by:

value = input || (input.blank? ? "default" : input)
# I just tried that the parentheses are required, or else its return is incorrect

For pure ruby (not depending on Rails), you may use empty? like this:

value = input || (input.empty? ? "default" : input)

or like this (thanks @substantial for providing this):

value = (input ||= "").empty? ? "default" : input

6 Comments

I have another question -- it works great if we have input actually defined somewhere. But what if we don't? So, all we get is 'undefined local variable or method' ?
@DmitriyUgnichenko updated the answer, see if it answer you question :)
@PeterWong Nope, it didn't. Still having undefined input.
@DmitriyUgnichenko value = (input ||= "").blank? ? "default" : input This will set input to an empty string if undefined.
Yeah, extend the core Object class to include blank? just like Rails does. Ask a new question if you need further help.
|
0

Maybe irrelavant but I would use highline like this:

require "highline/import"

input = ask('Input: ') { |q| q.default = "default" }

It works without Rails. Really neat solution.

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.