Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Object#blank? vs. String#empty? confusion

Rails docs have this information for Object#blank?

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

But the source for that method is like this:

# File activesupport/lib/active_support/core_ext/object/blank.rb, line 12
def blank?
    respond_to?(:empty?) ? empty? : !self
end

Now, when I open my handy little command line and type ruby -e 'p " ".empty?' it returns false. That means that Rails should say this is a blank value when it's clearly not. But! I open my rails console and I type " ".empty? and get false like my earlier straight command line. But, I type " ".blank? and I get true like Rails promises me.

What am I missing in understanding how Rails' blank? method works with the empty? method of String?

like image 788
jxpx777 Avatar asked Jan 27 '11 17:01

jxpx777


Video Answer


1 Answers

Rails is kinda tricky in how it documents its blank? method. Even though Object#blank? claims to also detect whitespace strings, it is implemented with String#blank? to handle the whitespace case and Object#blank? to catch the generic case. (blank? is defined on a few other classes, too, to save time.)

activesupport/lib/active_support/core_ext/object/blank.rb, line 66:

class String
  def blank?
    self !~ /\S/
  end
end
like image 160
Matchu Avatar answered Oct 05 '22 22:10

Matchu