I'm learning ruby (have a java/groovy background) and it looks like when writing methods, the method signature is
def method_name
# do something
end
With ruby's dynamic nature, I understand why the return type is not explicitly declared. But let's say I have a method called get_name. As a caller of the code, I may not be sure if it returns a String or some custom Name type. Is there a way to explicitly declare the return type? And (if it is possible) is this really ever done in ruby to make it clear what the return value is?
Update 2019: still no static typing or type annotations built into ruby, but we now have 3rd party type checkers. See this answer for more details.
Java performs static type checks. It ensures at compile time that all type requirements are met. Ruby is more dynamic, it doesn't do compile time checks and its type system is often referred to as "duck typing". That is, "If it walks like a duck and quacks like a duck, then it must be a duck".
If a method expects an object that responds to certain messages (has certain methods), then it doesn't care about actual type of the object as long it conforms to the protocol. If this is backed up by good test suite, then it's (arguably) a better way, because it allows for faster prototyping and reduced visual clutter. Less visual clutter - code is more expressive and understandable. Benefits of that are obvious. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With