Fri 3 Aug 2007
Beautiful Ruby: Learning the -isms
Posted by nola under Ruby, Uncategorized
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:
-
response = Net::HTTP.get_response(URI.parse("http://myawesomesite")
-
if response.body.match("my awesome text") == nil then
-
return false
-
end
and remember to do:
-
response = Net::HTTP.get_response(URI.parse("http://myawesomesite")
-
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:
-
color = red
-
if (color == "red") or (color =="green") or (color == "yellow") then
-
print "its valid)
-
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:
-
color = red
-
valid_values = ["red","green","yellow"]
-
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

August 4th, 2007 at 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.
August 8th, 2007 at 5:41 am
right.. thanks Peter!
September 26th, 2007 at 8:16 pm
I was going to say exactly what Peter said.