Monday, July 22, 2019

ruby - 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?


Answer



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

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...