Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby object blank? method

Can someone explain in details this Object method (I mean syntax used here :empty? , !!empty? and !self) :

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

Or maybe advise good book to read on topic.

like image 824
Andriy V Avatar asked Nov 25 '25 14:11

Andriy V


1 Answers

if self has got method empty? then return double not empty? otherwise return single not self.

not (!) is an idiomatic way in Ruby to convert any object into Boolean

single not (!) returns false for any truthy and true for any falsey object.

double not (!!) returns true for any truthy and false for any falsey object.

Falsey objects in Ruby are nil and false, any other objects are truthy.

So. Essentially respond_to?(:empty?) ? !!empty? : !self checks if current object has defined method empty? and returns true if this method returns anything truthy or false in case of falsey response. If empty? is not defined it will always return false if self is not false or nil (any falsey object).

like image 137
fl00r Avatar answered Nov 27 '25 15:11

fl00r