Matt Gushee wrote:
programmers. So I’d like to hear what people think about the following:
- The ability to modify existing class and module definitions is
obviously interesting, but what is it useful for? I can see
that this feature allows you to change the behavior of all instances
of a class; what, if any, other benefits are there? Does anyone have
some real-world application scenarios where this feature is useful?
You can mix Ruby methods and methods defined by a C-extension.
Meta-programming: You have some functions which dynamically modify the
classes to prevent you from doing repetative tasks for different classes.
You can extend the functionality of built in classes or
classes which are sourced from an already intalled file. Decreases the
number of classes to maintain -> Shortens class names -> Makes code
You can override methods (for example logging) and globally
change the functionality of existing objects.
- As above, for adding instance-specific methods.
If you want that a special object handles some situation specially.
This could be solved by defining a new class. In Ruby, this is
not needed and you don’t have to coin a new name. -> Shortens
class names -> Makes code more readable.
- Regarding iterators: it is clearly often more elegant to use an
iterator rather than a for or while loop. Does the existence of
iterators provide any benefit to end users (e.g. performance)?
This is one of the most important features of Ruby:
You can iterate over a collection without knowing its internal structure.
In C,C++, you could solve this by using a function pointer or a virtual
function. The problem is that normally you need some external data additionally
in your iterator function.
(The context) So in C e.g. you have to define a context pointer or a
variable argument list. So, you have to decleare your context structure (class).
This means, that you normally need at least 10 lines
to do a simple iteration (which takes several minutes to write, test and debug),
whereas in Ruby, you just need 1 line.
I think its performance is not better (or even worse) than a low level
iteration using informations about the internal structure. But its readablility
and maintainability is much much better.
I think, the best thing for you to do is to write 10 small Ruby programms and
you will recognize the advantage of iterators.
Best Regards, Christian