Difference between revisions of "Programming in D for Ruby Programmers"

From D Wiki
Jump to: navigation, search
 
(3 intermediate revisions by 2 users not shown)
Line 8: Line 8:
 
*[https://rounin.livejournal.com/24639.html David Oftedal writes on Project Euler problem 61: from Ruby to D]
 
*[https://rounin.livejournal.com/24639.html David Oftedal writes on Project Euler problem 61: from Ruby to D]
 
*[https://www.google.de/search?q=ruby&domains=dlang.org&sourceid=google-search&sitesearch=forum.dlang.org&gws_rd=cr&ei=fT0kVdbAD8H6sAHFrYDwBQ#q=ruby+site:forum.dlang.org&domains=dlang.org&start=10 forum posts on Ruby]
 
*[https://www.google.de/search?q=ruby&domains=dlang.org&sourceid=google-search&sitesearch=forum.dlang.org&gws_rd=cr&ei=fT0kVdbAD8H6sAHFrYDwBQ#q=ruby+site:forum.dlang.org&domains=dlang.org&start=10 forum posts on Ruby]
 +
*[https://wiki.dlang.org/Call_D_from_Ruby_using_FFI Call D Functions Using Ruby FFI]
  
 
== Adding methods to existing classes / UFCS ==
 
== Adding methods to existing classes / UFCS ==
Line 33: Line 34:
 
void underline(string s) {
 
void underline(string s) {
 
     import std.stdio : writeln;
 
     import std.stdio : writeln;
     import std.array : replicate;
+
     import std.range : repeat;
 
     writeln(s);
 
     writeln(s);
     writeln("=".replicate(s.length));
+
     writeln('='.repeat(s.length));
 
}
 
}
 
+
 
void main() {
 
void main() {
 
     "Hello, world!".underline();
 
     "Hello, world!".underline();
 
}
 
}
 
</source>
 
</source>
 +
 +
[[Category:Languages versus D]]

Latest revision as of 23:34, 4 August 2016

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
    end
end

"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;
    writeln(s);
    writeln('='.repeat(s.length));
}
 
void main() {
    "Hello, world!".underline();
}