The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My work

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,816 other followers

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

 

One Response to “RubyMania has reached Delphi – Times helper method implementation for integers – from Asbjørn Heid”

  1. That wasn’t intended as encouragement… :P

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: