Beautiful Ruby: Learning the -isms

I did PHP for 6 years.... sometimes its hard not to do PHP in ruby...

Today i was testing a url to see if it contains a certain string:

RUBY:
  1. response = Net::HTTP.get_response(URI.parse("http://myawesomesite")
  2. if response.body.match("my awesome text") == nil  then
  3.       return false
  4. end

and remember to do:

RUBY:
  1. response = Net::HTTP.get_response(URI.parse("http://myawesomesite")
  2. return "false" if response.body.match("my awesome text").nil?

Another thing I was working on was I had to do a multiple if statement

I will simplify it for this example:

RUBY:
  1. color = red
  2.   if (color == "red") or (color =="green") or (color == "yellow") then
  3.     print "its valid)
  4. end

In PHP I might have actually made the values into an array, and then did in_array ... but in reading the code, you see below, if in the valid values, print something. I don't want to see array!

This is more elegant:

RUBY:
  1. color = red
  2. valid_values = ["red","green","yellow"]
  3. puts "its valid" if valid_values.include? color

This seems to only work for values you'd do == on, not ===

See... programming in ruby just makes me grin :)

3 Comments »

  1. Peter Harkins Said,

    August 4, 2007 @ 11:54 am

    You have a typo in one of your first pair of examples: in the first one you return boolean false, in the second you return the string “false”.

    Also, I’d want to write the second line of the second example as:
    return false unless response.body.match “my awesome text”

    It’s just a little easier to read; it works because nil and false are considered false in if/unless tests.

  2. nola Said,

    August 8, 2007 @ 5:41 am

    right.. thanks Peter!

  3. Shane Vitarana Said,

    September 26, 2007 @ 8:16 pm

    I was going to say exactly what Peter said.

RSS feed for comments on this post · TrackBack URI

Leave a Comment