PHP style boolean expressions with Ruby

8 01 2008

I’ve come to ruby and rails from php. By and large I’m loving the switch but a few things I miss. One of the big ones is that ruby evaluates an empty string and the number 0 to be true in boolean expressions.

So I wrote a quick way around it.

class String

  def to_b

    self.length > 0

  end

endclass Integer

  def to_b

    self != 0

  end

end

Now if you want to check if a string or integer would be considered false by PHP just call to_b on it. Example:

"Desu".to_b #true

"".to_b #false

10.to_b #true

0.to_b #false

Simple but it does the job .

Update: You can just use empty? for strings

Advertisements