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:
-
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:
RUBY:
-
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:
RUBY:
-
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:
RUBY:
-
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
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.
nola Said,
August 8, 2007 @ 5:41 am
right.. thanks Peter!
Shane Vitarana Said,
September 26, 2007 @ 8:16 pm
I was going to say exactly what Peter said.