Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can set default value for nill or empty string? #6

Open
nvtin opened this issue Jul 10, 2017 · 0 comments
Open

How can set default value for nill or empty string? #6

nvtin opened this issue Jul 10, 2017 · 0 comments

Comments

@nvtin
Copy link
Owner

nvtin commented Jul 10, 2017

We usually do:

 if input = nil
 value = input || 'default'
 => value = 'default'

But if input is not nil, it is empty string: input = ''

 if input = ''
 value = input || 'default'
 => value = ''

How can we set default value for empty string ?

  1. we can use if like:
value = input.present? ? input : 'default'
  1. Another way to do it without if.
    Rails adds presence method to all object that does exactly what you want
    See below to use presence:
input = ''
value = input.presence || "default"
=> "default"

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

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

^_^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant