Here’s a real excerpt (slightly modified to protect the stupid, and now fixed) from a web app I inherited. GRAAAAAAAARGH!
def encrypt_password
...
self.salt = md5("#{Time.now.to_s}-#{login}")
...
end
def generate_confirm_hash
...
self.confirm_hash = md5("#{Time.now.to_s}-#{email}")
..
end
Pro-tip for hiring managers: ask candidates to identify problems in the above code, and smack any who fail to do so.
Uncategorized
CS, Programming, Ruby, Security
All right, class. Who can tell me what the following program will output? Bear with me, I promise this gets interesting.
1
2
3
4
5
6
| int main ()
{
int x = 0, y = 0;
y = ++x + 10;
printf("%d, %d\n", x, y);
} |
That’s easy, it’s exactly what you expect: “1, 11″.
What about if you replace line 4 with the following?
Again, easy! This time, the expression x++ evaluates to the value of x before it is incremented, so the answer is “1, 10″.
Now, what about this?
1
2
3
4
5
6
| int main ()
{
int x = 0;
x = ++x + 10;
printf("%d\n", x);
} |
This is no different than the first example, except that we’ve chucked the variable y, so the answer is “11″.
Last question: (and I’m sure you can see where this is going) what if you replace line 4 with the following?
I’m obviously trying to trick you, so you must realize that the answer is surprisingly also “11″, but can anyone tell me why it is so?
Extra credit: explain what happens if you replace line 4 with this seemingly-equivalent statement:
Uncategorized
CS, Programming
Ruby is a wonderful language, largely deserving of the fanaticism surrounding it. There are a number of ways you can exploit its syntax to write concise, beautiful code. For example, to shuffle an array…
…or to pick out certain elements of one…
deck.find_all{ |card| card.suit == Clubs }
…or to seamlessly cache computations.
def average_earnings
@average_earnings ||= some_lengthy_computation
end
(Above, the ||= operator acts analogously to the familiar += operator. So if the instance variable @average_earnings already has a non-nil value, it is returned without any further computation. If on the other hand it is nil, then some_lengthy_computation is performed, @average_earnings is set to it, and returned.)
In addition, there are also a number of ridiculously short applications written in it, including a web server in 70 lines of code, a message board application in 500 lines, and its slightly more verbose successor.
In addition to these, I present a proof of concept of my own: Mathematica and Maple-like symbolic differentiation in about a hundred lines of code.
Read more…
Uncategorized
CS, Math, Programming, Ruby