Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Friday, May 15, 2009

Google Operator Observation

I was writing a small Ruby program and with out thinking wrote:

count++

Which of course produces a : :syntax error !! when executed. Duh, Ruby does not have pre/post increment/decrement operators.

I wanted to find more information about this, so I started with Google, typed in ruby ++ and hit search.


That's cool the suggestion for 'Ruby ++' is 'Ruby increment'. So Google recognises programming operators?, not exactly. I could not get the same suggestions for other operators.

Other words like 'test ++' did not give a 'test increment' suggestion. Other programming languages did produce this like 'perl ++' but others didn't like 'java ++'.

I couldn't find alot of information on the 'See results for' feature. My guess is that a 'programming language name' and '++' and 'increment' must show up together in alot of webpages and Google is not doing some cool operator interpretation, ... sad.

Thursday, February 26, 2009

MD5 hash, Java vs Ruby

I needed to create a small program that would create a MD5 hexadecimal hash for a password. First I implemented this using Java.

import java.security.MessageDigest;
public class TestMD5 {
public static void main (String [] args) {
try {
String passwd = "password";
MessageDigest md =
MessageDigest.getInstance("MD5");
byte[] hash = md.digest(passwd.getBytes());
StringBuffer hexstr = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(
hash[i] & 0xFF);
if (hex.length() == 1) {
hexstr.append('0');
}
hexstr.append(hex);
}
System.out.println(hexstr.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


Note: java.lang.Integer.toHexString does not add leading zeros. Without the length check after this function the hash string will not always be 32 charaters long.


Since I have started working with Ruby on Rails, I was curious to see how I would implement this in Ruby.

#!/usr/bin/ruby
require 'digest/md5'
passwd = "password"
digest = Digest::MD5.hexdigest(passwd)
puts digest


In this case Ruby wins for having to write less code to get the same result.