RubyMania has reached Delphi – Times helper method implementation for integers – from Asbjørn Heid
Posted by jpluimers on 2016/04/21
The below fragment is one of the favourite kinds of examples in the Ruby world:
5.times { |i| print i, " " }
It uses the times method on Integer and prints:
0 1 2 3 4
There are many implementations of this in other languages, for instance Ruby’s ‘times()’ function in C# | Of Code and Me (which the WordPress.com editor fucked up as it replaced Action<int> with Action which is a totally different thing, so the gist with code is below.
public static class IntExtensions { public static void Times(this int i, Action func) { for(int j = 0; j < i; j++) { func(j); } } }
Which you use as
5.Times(i => Console.Write(i));
It’s slightly off as it prints:
01234
I know; nitpicking, but this code works (did I ever tell I love .NET fiddle?):
5.Times(i => Console.Write("{0} ", i));
Well, Mason Wheeler encouraged Asbjørn Heid for the below Ruby Mania in Delphi; just read the comments at In C# nearly everything is an object, so when writing a unit test for a string…
Since the WordPress.com editor fucks up TProc<Integer> into TProc and TProc behaves differently from TProc<Integer>, I’ve included a gist link with the actual code below.
program RubyManiaConsoleProject; uses System.SysUtils; type TRubyMania = record helper for ShortInt procedure times(const IterBody: TProc); end; procedure TRubyMania.times(const IterBody: TProc); var i: Integer; begin for i := 0 to Self-1 do IterBody(i); end; begin 5.times( procedure(i: Integer) begin Write(i, ' '); end ); end.
It also shows why I hardly use anonymous methods in Delphi: they’re way too verbose.
–jeroen
using System; | |
public static class IntExtensions | |
{ | |
public static void Times(this int i, Action<int> func) | |
{ | |
for(int j = 0; j < i; j++) | |
{ | |
func(j); | |
} | |
} | |
} | |
public class Program | |
{ | |
public static void Main() | |
{ | |
5.Times(i => Console.Write("{0} ", i)); | |
} | |
} |
program RubyManiaConsoleProject; | |
uses | |
System.SysUtils; | |
type | |
TRubyMania = record helper for ShortInt | |
procedure times(const IterBody: TProc<Integer>); | |
end; | |
procedure TRubyMania.times(const IterBody: TProc<Integer>); | |
var | |
i: Integer; | |
begin | |
for i := 0 to Self-1 do | |
IterBody(i); | |
end; | |
begin | |
5.times( | |
procedure(i: Integer) | |
begin | |
Write(i, ' '); | |
end | |
); | |
end. |
Mason Wheeler said
That wasn’t intended as encouragement… :P