Right after I gave my ?Refactoring
your code - a key step in agility? talk at NFJS, Milwaukee
last week, a
gentleman asked my opinion about Ruby syntax being confusing and cryptic.
The first time I look at Ruby, I have to admit, it did look, should I say ?different??
But then again, the first
time I look at just about anything, it looked different.
No matter which language you pick, you need to take the time to get used to its nuances.
While Ruby syntax is different from Java (or C#) syntax, the reason I like it is its
simplicity and lack of
clutter. I find it easier to get things done in Ruby than in other languages I am
used to.
Perl is pretty cryptic?many have called it ?a write only language.? If you say Ruby
is cryptic, I say yes, it
is cryptic enough to please me!
Yesterday, I was looking at a Java API. I was not sure, from the method call, if it
was a query or if it
modified the object. In Ruby, an exclamation at the end of the method conveys that
it?s a mutator.
Once you get used to the language, you will see it feels right and light.
Consider a simple example. I want a method to take a series of numbers and tells me
how many
numbers in it are less than a pivot and how many are more.
Here is Java code to do that (along with an example of its usage):
public static void lessAndMore(int pivot,
Integer[] result, int...
vals)
{
if (result
!= null &&
result.length == 2 && vals.length > 0)
{ // Need to worry about result being null or not being
size 2.
int less = 0;
int more = 0;
for(int val
: vals)
{
if (val
< pivot) less++;
if (val
> pivot) more++;
}
result[0] = less;
result[1] = more;
}
}
public static void main(String[]
args) throws IllegalAccessException, InstantiationException
{
Integer[] result = new Integer[2];
lessAndMore(5, result, 8, 2, 4, 3, 3, 9, 3, 2, 1, 9, 5);
System.out.println("Less
= " + result[0]);
System.out.println("More
= " + result[1]);
}
In Java, I can?t pass primitive types by reference. So, I had to send an array of
Integers and receive the
result back.
Here is C# code to do the same:
public static void LessAndMore(int pivot,
out int less, out int more, params int[]
vals)
{
less = more = 0;
if (vals.Length
> 0)
{
foreach(int val in vals)
{
if (val
< pivot) less++;
if (val
> pivot) more++;
}
}
}
static void Main(string[]
args)
{
int less,
more;
LessAndMore(5, out less, out more,
8, 2, 4, 3, 3, 9, 3, 2, 1, 9, 5);
Console.WriteLine("Less={0}",
less);
Console.WriteLine("More={0}",
more);
}
Ruby code for the same:
def
lessAndMore(pivot, vals)
less = 0
more = 0
vals.each { |val|
if val
< pivot then less += 1 end
if val
> pivot then more += 1 end
}
return less,
more
end
less, more = lessAndMore(5,
[8, 2, 4, 3, 3, 9, 3, 2, 1, 9, 5]);
puts "Less
= #{less}"
puts "More
= #{more}"
I like the ability to return multiple values.
"Ruby is concise without being unintelligibly terse..." [Words from Agile Web Development with Rails].