Caley Woods
Caley Woods

Reputation: 4737

Duplicating .blank? in standard Ruby

Rails has a .blank? method that will return true if an Object is empty? or nil?. The actual code for this can be found here. When I try on 1.9.2 to duplicate this by doing:

class Object

  def blank?
    respond_to?(:empty?) ? empty? : !self
  end

end

Calling "".blank? returns true but calling " ".blank? returns false when according to the rails documentation a whitespace string should eval to true for .blank? Before I looked up the code I originally wrote:

class Object

  def blank?
    !!self.empty? || !!self.nil?
  end

end

and had the same results. What am I missing?

Upvotes: 6

Views: 836

Answers (3)

Matheus Moreira
Matheus Moreira

Reputation: 17020

The String class overrides the Object implementation of blank? in Rails's implementation:

class String

  def blank?
    # Blank if this String is not composed of characters other than whitespace.
    self !~ /\S/ 
  end

end

Upvotes: 2

Peter
Peter

Reputation: 132257

Strings are not classed as empty? if they are full of spaces only

>> "  ".empty?
=> false

Therefore, you may wish to also create

class String
  def blank?
    strip.empty?
  end
end

But think carefully about this - monkey patching like this is hazardous, especially if other modules will use your code.

Upvotes: 1

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

You forget about this - https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/blank.rb#L95

class String
  # A string is blank if it's empty or contains whitespaces only:
  #
  #   "".blank?                 # => true
  #   "   ".blank?              # => true
  #   " something here ".blank? # => false
  #
  def blank?
    self !~ /\S/
  end
end

Upvotes: 13

Related Questions