Ruby/Rails Using || to Determine Value, Using an Empty String Instead of a Nil Value

Ruby/Rails using || to determine value, using an empty string instead of a nil value

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"

Rails ||= for empty strings

you can try like this:

@my_var = ''
@my_var = @my_var.presence || 'This is a non-empty string'

Thanks :-)

Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.

Ruby way to check if a string is not blank?

string = ""

unless string.to_s.strip.empty?
# ...

Converting an empty string to nil in place?

The clean way is using presence.

Let's test it.

'    '.presence
# => nil

# => nil

# => "text"

# => nil

# => nil

# => nil

# => true

# => nil

Please note this method is from Ruby on Rails v4.2.7

Rails Model method check if field nil, if so return empty string

You can, although this might not be what you wanted, simply remove any nil objects from the address Array using the #compact method, so that #empty? will work...:

def full_address
[self.address1, self.address2, self.address3,, self.state, self.zipcode].compact.reject!(&:empty?).join(', ')

You should be aware that this WILL return a partial address if SOME of the fields exist.

I would probably void any fault addresses (in this example I require just the first address line and the city fields):

def full_address
return "" unless self.address1 && && !self.address1.empty? && !
[self.address1, self.address2, self.address3,, self.state, self.zipcode].compact.reject!(&:empty?).join(', ')

Disregarding the few edits I made to the code, I would probably go with @Joseph's #present? together with the validation, since you're using Rails:

def full_address
return "" unless self.address1 && && self.address1.present? &&
[self.address1, self.address2, self.address3,, self.state, self.zipcode].reject!(&:present?).join(', ')

Testing for an empty string in an ActiveRecord query

You can use this syntax:

Item.where(context: [nil, ''])

How to returns empty string instead of null in jbuilder views?

nil.to_s #=> "" so, you can simply add .to_s

If string is empty then return some default value

ActiveSupport adds a presence method to all objects that returns its receiver if present? (the opposite of blank?), and nil otherwise.


host = config[:host].presence || 'localhost'

Related Topics

Leave a reply