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


endclass Integer

  def to_b

    self != 0



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



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: