Its the little things.

I’ve been spending time with Ruby a bit lately and the more I learn, the more I like it.

One of the simple things that I learned early on is that everything is an expression (including if statements).

That allows you to do things like this:

new_value = if some_flag then calculated_value else default_value end

That’s a bit contrived. You’d probably use the ternary operator instead, but you could have blocks of code or methods executed in each step.

Its not huge, but its still much better than the Java way of:

if (someFlag) {
	newValue = calculatedValue
} else {
	newValue = defaultValue

Another simple thing that is huge is that Ruby sees “nil” (aka “null” in Java) as being “false” you can do nil checks elegantly like this:

my_var = some_func_that_might_return_nil(val_to_calc) || "default"

The code will get the value of “default” if the function call returns nil. Again, in Java you’d have something like:

String myVar = someFuncThatMightReturnNull(valToCal);
if (myVar == null) {
	myVar = "default";

Again its subtle, but it reads and flows much better to me.

Leave a Reply

Your email address will not be published. Required fields are marked *