Difference between revisions of "Programming in D for Ruby Programmers"
Line 33: | Line 33: | ||
void underline(string s) { | void underline(string s) { | ||
import std.stdio : writeln; | import std.stdio : writeln; | ||
− | import std. | + | import std.range : repeat; |
writeln(s); | writeln(s); | ||
− | writeln( | + | writeln('='.repeat(s.length)); |
} | } | ||
− | + | ||
void main() { | void main() { | ||
"Hello, world!".underline(); | "Hello, world!".underline(); | ||
} | } | ||
</source> | </source> |
Revision as of 09:13, 8 April 2015
This page is under community development.
In the meantime, you may find the following links of interest as a Ruby programmer:
- Ruby Programmer shares his excitement about D
- forum discussion of post
- Jacob Carlborg writes on embedding Ruby in a D application
- David Oftedal writes on Project Euler problem 61: from Ruby to D
- forum posts on Ruby
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();
}