Programming in D for Ruby Programmers

From D Wiki
Revision as of 23:34, 4 August 2016 by Bachmeier (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This page is under community development.

In the meantime, you may find the following links of interest as a Ruby programmer:

Adding methods to existing classes / UFCS

In Ruby, it's possible to add methods to existing classes, even builtin ones:

class String
    def underline
        puts self
        puts "=" * self.length

"Hello, world!".underline

# prints:
# Hello, world!
# =============

Because it uses a static compilation model, it's not possible to do exactly the same in D. However, D allows calling a free function as if it were a method, which mostly has the same effect from a caller's point of view, and has the additional advantage of not polluting the type's namespace:

void underline(string s) {
    import std.stdio : writeln;
    import std.range : repeat;
void main() {
    "Hello, world!".underline();