Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby parameter type confirmation

Coming from a Java background, I am a little perturbed by Ruby's completely blasé attitude toward its method parameters. Whereas in Java I could guarantee that parameter x was the type necessary for the method to work properly, in Ruby I have no way of guaranteeing that x is an integer, a string, or anything else for that matter.

Example: if I wanted to write an absolute_value method in Java, the header would be something like

public static int absoluteValue(int x)

In Ruby it would be something like

def self.absolute_value(x)

In this example, in the Java code I can be totally sure that the parameter being passed in isn't "Happy Birthday!" but in the Ruby code I don't know that. How do I prevent this situation in Ruby so the code doesn't crash at Runtime?

like image 430
Kvass Avatar asked Dec 22 '22 13:12

Kvass


1 Answers

Heh, welcome to Ruby. I too worked in Java in certain past years and I really loved Java at the time.

Now, it's not correct to think of Ruby as lacking type checking. It has at least as much type checking as Java, it's just that types are allowed to change and so the checks are done at runtime.

Plus, all that crushing declaration boilerplate in the old languages is annoying. A type-checked application that doesn't get finished in time to be useful does no one any good. A type-checked program that's too verbose to read is likely to become obsolete.

And if a type doesn't get checked the first time you run your Ruby program, it may well be covered by your tests.

But if you don't test it, you have no idea if it works anyway, so the abstract knowledge that the method call types conform would not be nearly as helpful as you might imagine.

In any case, Ruby has proven itself pretty well at this point as a language. As a real-life platform, RoR has some issues with performance, both in speed and in memory use, but I don't know of any projects complaining about the dynamic typing and wishing they were slogging through getting RSI with some old verbose language.

like image 193
DigitalRoss Avatar answered Jan 12 '23 08:01

DigitalRoss