Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicating .blank? in standard Ruby

Tags:

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?

like image 672
Caley Woods Avatar asked May 05 '11 17:05

Caley Woods


1 Answers

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
like image 61
Vasiliy Ermolovich Avatar answered Oct 07 '22 09:10

Vasiliy Ermolovich